示例#1
0
	string HRCReport::toStr(const Poco::DateTime& date) const{
            std::ostringstream ostr;
			string sDate;
			ostr << date.day() << "/" << date.month() << "/" << date.year();
			sDate = ostr.str();
			return sDate;
	}
void InactiveIdentityRequester::PopulateIDList()
{
	Poco::DateTime weekago;
	int id;
	int count=0;
	SQLite3DB::Transaction trans(m_db);

	weekago-=Poco::Timespan(7,0,0,0,0);
	weekago.assign(weekago.year(),weekago.month(),weekago.day(),0,0,0);

	// only selects, deferred OK
	trans.Begin();

	// select identities we want to query (haven't seen yet today) - sort by their trust level (descending) with secondary sort on how long ago we saw them (ascending)
	SQLite3DB::Statement st=m_db->Prepare("SELECT IdentityID FROM tblIdentity WHERE PublicKey IS NOT NULL AND PublicKey <> '' AND LastSeen IS NOT NULL AND LastSeen<? AND tblIdentity.FailureCount<=(SELECT OptionValue FROM tblOption WHERE Option='MaxFailureCount') AND (PurgeDate IS NULL OR PurgeDate>datetime('now')) ORDER BY RANDOM();");
	st.Bind(0, Poco::DateTimeFormatter::format(weekago,"%Y-%m-%d %H:%M:%S"));
	trans.Step(st);

	m_ids.clear();

	while(st.RowReturned())
	{
		st.ResultInt(0,id);
		m_ids[std::pair<long,long>(count,id)].m_requested=false;
		trans.Step(st);
		count+=1;
	}

	trans.Finalize(st);
	trans.Commit();
}
示例#3
0
	void ForecastParser::startElement(const Poco::XML::XMLString& namespaceURI, const Poco::XML::XMLString& localName, const Poco::XML::XMLString& qname,
			const Poco::XML::Attributes& attributes) {

		static std::map <int, int> hmap = hourMap();

		if (localName == "time"){
			int tz = 0;
			data.dateStr =  attributes.getValue("", "from");
			std::cout << data.dateStr << std::endl;
			Poco::DateTime dt;
			Poco::DateTimeParser::parse(data.dateStr, dt, tz);
			data.date = Poco::DateTime(
					dt.year(),
					dt.month(),
					dt.day(),
					hmap[dt.hour()]
			);
		}
		if (localName == "temperature"){
			data.temperature = Poco::NumberParser::parse(attributes.getValue("", "value"));
		}
		if (localName == "symbol"){
			data.img = Poco::NumberParser::parse(attributes.getValue("", "number"));
			data.info = attributes.getValue("", "name");
		}
		if (localName == "windSpeed"){
			data.wind = Poco::NumberParser::parseFloat(attributes.getValue("", "mps"));
		}
		if (localName == "precipitation"){
			data.precipitation = Poco::NumberParser::parseFloat(attributes.getValue("", "value"));
		}
	}
void SyslogParser::parseNew(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos)
{
	Poco::Message::Priority prio = convert(severity);
	// rest of the unparsed header is:
	// VERSION SP TIMESTAMP SP HOSTNAME SP APP-NAME SP PROCID SP MSGID
	std::string versionStr(parseUntilSpace(msg, pos));
	std::string timeStr(parseUntilSpace(msg, pos)); // can be the nilvalue!
	std::string hostName(parseUntilSpace(msg, pos));
	std::string appName(parseUntilSpace(msg, pos));
	std::string procId(parseUntilSpace(msg, pos));
	std::string msgId(parseUntilSpace(msg, pos));
	std::string message(msg.substr(pos));
	pos = msg.size();
	Poco::DateTime date;
	int tzd = 0;
	bool hasDate = Poco::DateTimeParser::tryParse(RemoteSyslogChannel::SYSLOG_TIMEFORMAT, timeStr, date, tzd);
	Poco::Message logEntry(msgId, message, prio);
	logEntry["host"] = hostName;
	logEntry["app"] = appName;
	
	if (hasDate)
		logEntry.setTime(date.timestamp());
	int lval(0);
	Poco::NumberParser::tryParse(procId, lval);
	logEntry.setPid(lval);
	_pListener->log(logEntry);
}
示例#5
0
void MongoDBTest::testInsertRequest()
{
	if (!_connected)
	{
		std::cout << "Not connected, test skipped." << std::endl;
		return;
	}

	Poco::MongoDB::Document::Ptr player = new Poco::MongoDB::Document();
	player->add("lastname", std::string("Braem"));
	player->add("firstname", std::string("Franky"));

	Poco::DateTime birthdate;
	birthdate.assign(1969, 3, 9);
	player->add("birthdate", birthdate.timestamp());

	player->add("start", 1993);
	player->add("active", false);

	Poco::DateTime now;
	std::cout << now.day() << " " << now.hour() << ":" << now.minute() << ":" << now.second() << std::endl;
	player->add("lastupdated", now.timestamp());

	player->add("unknown", NullValue());

	Poco::MongoDB::InsertRequest request("team.players");
	request.documents().push_back(player);
	_mongo.sendRequest(request);
}
	void run()
	{
		for(int i=0; i<kNumEnqueueByChild; ++i)
		{
			int counter = ++m_counter;
			Poco::DateTime datetime;
			datetime += Poco::Timespan(m_rnd.next(kScheduleMaxTime)*1000);
			m_queue.enqueueNotification(new ChildNotification(counter, m_name, datetime), datetime.timestamp());
			datetime.makeLocal(Poco::Timezone::tzd());
			m_msg.Message(Poco::format("   enqueueNotification #%d from %s (%s)"
										, counter
										, m_name
										, Poco::DateTimeFormatter::format(datetime.timestamp(), "%H:%M:%S.%i")));
		}
	}
int main()
{
	Poco::DateTime now;
	char szClientName[256] = { 0, };
	sprintf_s(szClientName, 256 - 1, "(%d-%d)", now.second(), now.millisecond());
		
	std::cout << "clinet(" << szClientName << ") 서버에 연결 시도..." << std::endl;
	Poco::Net::StreamSocket ss;

	try
	{
		ss.connect(Poco::Net::SocketAddress("localhost", PORT));

		for (int i = 0; i < 7; ++i)
		{
			char szMessage[256] = { 0, };
			sprintf_s(szMessage, 256 - 1, "%d, Send Message From %s", i, szClientName);
			auto nMsgLen = (int)strnlen_s(szMessage, 256 - 1);

			ss.sendBytes(szMessage, nMsgLen);

			std::cout << "서버에 보낸 메시지: " << szMessage << std::endl;


			char buffer[256] = { 0, };
			auto len = ss.receiveBytes(buffer, sizeof(buffer));

			if (len <= 0)
			{
				std::cout << "서버와 연결이 끊어졌습니다" << std::endl;
				break;
			}

			std::cout << "서버로부터 받은 메시지: " << buffer << std::endl;

			Poco::Thread::sleep(256);
		}

		ss.close();
	}
	catch (Poco::Exception& exc)
	{
		std::cout << "서버 접속 실패: " << exc.displayText() << std::endl;
	}
		
	getchar();
	return 0;
}
示例#8
0
void ClearHistory::Stop()
{


	if (!_stopped) {

		_rdbmsClearHis->stop();

		_stopped = true;
		Poco::DateTime dataTime;
		dataTime +=	10;
		ClearQueue.enqueueNotification(new ClearNotofication(0 ),dataTime.timestamp());
		_thread.join();
		ClearQueue.clear();
		g_pClearHistory = NULL;
	}
}
示例#9
0
    void TextSerializer::dump()
    {
        if (buffer.size() == 0)
            return;

        Poco::DateTime date = buffer[0]->DateTime;
        string file = Poco::format("%s/%04d%02d%02d.csv", path, date.year(), date.month(), date.day());

        std::ofstream os;
        os.open (file, std::ofstream::out | std::ofstream::app);

        for (int i = 0; i < buffer.size(); i++)
            os << serTick(buffer[i]);

        os << std::flush;
        os.close();
    }
示例#10
0
//----------------------------------------
//	main
//----------------------------------------
int main(int /*argc*/, char** /*argv*/)
{
	PrepareConsoleLogger logger(Poco::Logger::ROOT, Poco::Message::PRIO_INFORMATION);

	ScopedLogMessage msg("DateTimeTest ", "start", "end");

	Poco::DateTime dateTime;

	msg.Message("  Current DateTime (UTC)");
	DisplayDateTime(dateTime, msg);

	msg.Message(Poco::format("  Current DateTime (Locat Time: %s [GMT%+d])", Poco::Timezone::name(), Poco::Timezone::tzd()/(60*60)));
	dateTime.makeLocal(Poco::Timezone::tzd());
	DisplayDateTime(dateTime, msg);

	msg.Message(Poco::format(Poco::DateTimeFormatter::format(dateTime, "  DateTimeFormatter: %w %b %e %H:%M:%S %%s %Y")
				,	Poco::Timezone::name()));

	return 0;
}
示例#11
0
void TrustListInserter::CheckForNeededInsert()
{
	Poco::DateTime date;
	int currentday=date.day();
	date-=Poco::Timespan(0,6,0,0,0);
	// insert trust lists every 6 hours - if 6 hours ago was different day then set to midnight of current day to insert list today ASAP
	if(currentday!=date.day())
	{
		date.assign(date.year(),date.month(),currentday,0,0,0);
	}

	SQLite3DB::Statement st=m_db->Prepare("SELECT LocalIdentityID, PrivateKey FROM tblLocalIdentity WHERE tblLocalIdentity.Active='true' AND PrivateKey IS NOT NULL AND PrivateKey <> '' AND PublishTrustList='true' AND InsertingTrustList='false' AND (LastInsertedTrustList<=? OR LastInsertedTrustList IS NULL);");
	st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
	st.Step();

	if(st.RowReturned())
	{
		int lid=0;
		std::string pkey("");
		st.ResultInt(0,lid);
		st.ResultText(1,pkey);
		StartInsert(lid,pkey);
	}

}
示例#12
0
    CThostFtdcDepthMarketDataField* Exchange::GenTick()
    {
        Poco::DateTime now;
        string date = Poco::format("%02d%02d%02d", now.year(), now.month(), now.day());
        string time = Poco::format("%02d:%02d:%02d", now.hour(), now.minute(), now.second());

        strcpy(tick->TradingDay, date.c_str());
        strcpy(tick->UpdateTime, time.c_str());
        strcpy(tick->InstrumentID, INSTRUMENT);
        tick->UpdateMillisec = now.millisecond();
        tick->LastPrice = RandomWalk(tick->LastPrice);
        tick->Volume = tick->Volume;
        return tick;
    }
示例#13
0
    char* prefix(char* buffer, const std::size_t len, const char* level)
    {
        const char *threadName = Util::getThreadName();
#ifdef __linux
        const long osTid = Util::getThreadId();
#elif defined IOS
        const auto osTid = pthread_mach_thread_np(pthread_self());
#endif
        Poco::DateTime time;
        snprintf(buffer, len, "%s-%.05lu %.4u-%.2u-%.2u %.2u:%.2u:%.2u.%.6u [ %s ] %s  ",
                    (Source.getInited() ? Source.getId().c_str() : "<shutdown>"),
                    osTid,
                    time.year(), time.month(), time.day(),
                    time.hour(), time.minute(), time.second(),
                    time.millisecond() * 1000 + time.microsecond(),
                    threadName, level);
        return buffer;
    }
void IntroductionPuzzleInserter::CheckForNeededInsert()
{
	// only do 1 insert at a time
	if(m_inserting.size()==0)
	{
		// select all local ids that aren't single use and that aren't currently inserting a puzzle and are publishing a trust list
		SQLite3DB::Statement st=m_db->Prepare("SELECT LocalIdentityID FROM tblLocalIdentity WHERE tblLocalIdentity.Active='true' AND PublishTrustList='true' AND SingleUse='false' AND PrivateKey IS NOT NULL AND PrivateKey <> '' ORDER BY LastInsertedPuzzle;");
		st.Step();

		// FIXME Convert to nested SELECT
		SQLite3DB::Statement st2=m_db->Prepare("SELECT UUID FROM tblIntroductionPuzzleInserts WHERE Day=? AND FoundSolution='false' AND LocalIdentityID=?;");

		while(st.RowReturned())
		{
			int localidentityid=0;
			std::string localidentityidstr="";
			Poco::DateTime now;
			float minutesbetweeninserts=0;
			minutesbetweeninserts=1440.0/(float)m_maxpuzzleinserts;
			Poco::DateTime lastinsert=now;
			lastinsert-=Poco::Timespan(0,0,minutesbetweeninserts,0,0);

			st.ResultInt(0, localidentityid);
			StringFunctions::Convert(localidentityid, localidentityidstr);

			// if this identity has any non-solved puzzles for today, we don't need to insert a new puzzle
			st2.Bind(0, Poco::DateTimeFormatter::format(now,"%Y-%m-%d"));
			st2.Bind(1, localidentityid);
			st2.Step();

			// identity doesn't have any non-solved puzzles for today - start a new insert
			if(!st2.RowReturned())
			{
				// make sure we are on the next day or the appropriate amount of time has elapsed since the last insert
				std::map<int,Poco::DateTime>::iterator i;
				if((i=m_lastinserted.find(localidentityid))==m_lastinserted.end() || (*i).second<=lastinsert || (*i).second.day()!=now.day())
				{
					StartInsert(localidentityid);
					m_lastinserted[localidentityid]=now;
				}
				else
				{
					m_log->trace("IntroductionPuzzleInserter::CheckForNeededInsert waiting to insert puzzle for "+localidentityidstr);
				}
			} else {
				st2.Reset();
			}

			st.Step();
		}
	}
}
示例#15
0
void MongoDBTest::testInsertRequest()
{
	Poco::MongoDB::Document::Ptr player = new Poco::MongoDB::Document();
	player->add("lastname", std::string("Braem"));
	player->add("firstname", std::string("Franky"));

	Poco::DateTime birthdate;
	birthdate.assign(1969, 3, 9);
	player->add("birthdate", birthdate.timestamp());

	player->add("start", 1993);
	player->add("active", false);

	Poco::DateTime now;
	player->add("lastupdated", now.timestamp());

	player->add("unknown", NullValue());

	Poco::MongoDB::InsertRequest request("team.players");
	request.documents().push_back(player);
	_mongo->sendRequest(request);
}
示例#16
0
void Utility::dateTimeSync(SQL_TIMESTAMP_STRUCT& ts, const Poco::DateTime& dt)
{
	ts.year = dt.year();
	ts.month = dt.month();
	ts.day = dt.day();
	ts.hour = dt.hour();
	ts.minute = dt.minute();
	ts.second = dt.second();
	// Fraction support is limited to milliseconds due to MS SQL Server limitation
	// see http://support.microsoft.com/kb/263872
	ts.fraction = (dt.millisecond() * 1000000);// + (dt.microsecond() * 1000);
}
示例#17
0
void Utility::dateTimeSync(Poco::DateTime& dt, const SQL_TIMESTAMP_STRUCT& ts)
{
	double msec = ts.fraction/1000000;
	double usec = 1000 * (msec - std::floor(msec));

	dt.assign(ts.year,
		ts.month,
		ts.day,
		ts.hour,
		ts.minute,
		ts.second,
		(int) std::floor(msec),
		(int) std::floor(usec));
}
示例#18
0
Poco::DateTime CSunRiseSet::GetSolarNoon(double dLon, Poco::DateTime time) 
{ 
	bool bLeap = IsLeapYear(time.year()); 
	 
	int iJulianDay = CalcJulianDay(time.month(),time.day(),bLeap); 
 
	double timeGMT = calcSolNoonGMT(iJulianDay, dLon);  
 
	double dHour = timeGMT / 60; 
	int iHour = (int)dHour; 
	double dMinute = 60 * (dHour - iHour); 
	int iMinute = (int)dMinute; 
	double dSecond = 60 * (dMinute - iMinute); 
	int iSecond = (int)dSecond; 
	 
	Poco::DateTime NewTime(time.year(),time.month(),time.day(),iHour,iMinute,iSecond); 
	NewTime.makeLocal(Poco::Timezone::tzd() - Poco::Timezone::dst()); 
	return NewTime;
} 
示例#19
0
Poco::DateTime CSunRiseSet::GetSunrise(double dLat,double dLon, Poco::DateTime time) 
{ 
	bool bLeap = IsLeapYear(time.year()); 
	 
	int iJulianDay = CalcJulianDay(time.month(),time.day(),bLeap); 
 
	double timeGMT = calcSunriseGMT(iJulianDay, dLat,dLon);  
 
 
	// if Northern hemisphere and spring or summer, use last sunrise and next sunset 
	if ((dLat > 66.4) && (iJulianDay > 79) && (iJulianDay < 267)) 
		timeGMT = findRecentSunrise(iJulianDay, dLat, dLon); 
	// if Northern hemisphere and fall or winter, use next sunrise and last sunset 
	else if ((dLat > 66.4) && ((iJulianDay < 83) || (iJulianDay > 263))) 
		timeGMT = findNextSunrise(iJulianDay, dLat, dLon); 
	// if Southern hemisphere and fall or winter, use last sunrise and next sunset 
	else if((dLat < -66.4) && ((iJulianDay < 83) || (iJulianDay > 263))) 
		timeGMT = findRecentSunrise(iJulianDay, dLat, dLon); 
	// if Southern hemisphere and spring or summer, use next sunrise and last sunset 
	else if((dLat < -66.4) && (iJulianDay > 79) && (iJulianDay < 267)) 
		timeGMT = findNextSunrise(iJulianDay, dLat, dLon); 
//	else  
//	{ 
		//("Unaccountable Missing Sunrise!"); 
//	} 
	 
	 
	double dHour = timeGMT / 60; 
	int iHour = (int)dHour; 
	double dMinute = 60 * (dHour - iHour); 
	int iMinute = (int)dMinute; 
	double dSecond = 60 * (dMinute - iMinute); 
	int iSecond = (int)dSecond; 
	 
	Poco::DateTime NewTime(time.year(),time.month(),time.day(),iHour,iMinute,iSecond); 
	NewTime.makeLocal(Poco::Timezone::tzd() - Poco::Timezone::dst()); 
	return NewTime;
} 
示例#20
0
    /* Function to populate TSK Blackboard exif related attributes */
    void extractExifData(ExifData * exifData, TskFile * pFile)
    {
        std::map<ExifTag, TSK_ATTRIBUTE_TYPE>::iterator it;
        std::vector<TskBlackboardAttribute> attrs;
        std::string datetime = "";
        int timezone = 0;

        for (it = tagMap.begin(); it != tagMap.end(); ++it)
        {
            ExifEntry * exifEntry = exif_data_get_entry(exifData, it->first);
            char tag_data[256];

            if (exifEntry == NULL)
                continue;

            if (it->first == EXIF_TAG_GPS_LATITUDE ||
                it->first == EXIF_TAG_GPS_LONGITUDE)
            {
                // Check for the EXIF_IFD_GPS image file directory to avoid interoperability value
                ExifIfd ifd = exif_entry_get_ifd(exifEntry);
                if (ifd != EXIF_IFD_GPS)
                    continue;

                exif_entry_get_value(exifEntry, tag_data, 256);

                float decDegrees = getDecimalDegrees(tag_data);

                char refValue[2];

                if (it->first == EXIF_TAG_GPS_LATITUDE)
                {
                    // Get the latitude reference value; used to determine if positive or negative decimal value
                    ExifEntry * latitudeRef = exif_data_get_entry(exifData, it->first);
                    exif_entry_get_value(latitudeRef, refValue,2);

                    if (strcmp(refValue, "S") == 0)
                        decDegrees *= -1;
                }
                else
                {
                    // Get the longitude reference value; used to determine if positive or negative decimal value
                    ExifEntry * longitudeRef = exif_data_get_entry(exifData, it->first);
                    exif_entry_get_value(longitudeRef, refValue,2);

                    if (strcmp(refValue, "W") == 0)
                        decDegrees *= -1;
                }
                
                TskBlackboardAttribute attr(it->second, name(), "", decDegrees);
                attrs.push_back(attr);                
            }
            else if (it->first == EXIF_TAG_GPS_SPEED)
            {
                // Check for the EXIF_IFD_GPS image file directory to avoid interoperability value
                ExifIfd ifd = exif_entry_get_ifd(exifEntry);
                if (ifd != EXIF_IFD_GPS)
                    continue;

                //Get the GPS speed value
                exif_entry_get_value(exifEntry, tag_data, 256);

                float speed = getGPSSpeed(tag_data);

                char refValue[2];

                //Get the GPS speed reference value
                ExifEntry * speedRef = exif_data_get_entry(exifData, it->first);
                exif_entry_get_value(speedRef, refValue,2);

                //Convert Kilometers per hour to meters per second 
                if (strcmp(refValue, "K") == 0)
                {
                     speed *= 0.277778;
                }
                //Convert Miles per hour to meters per second 
                if (strcmp(refValue, "M") == 0)
                {
                    speed *= 0.44704;
                }
                //Convert Knots to meters per second
                if (strcmp(refValue, "N") == 0)
                {
                    speed *= 0.514444;
                }
                
                TskBlackboardAttribute attr(it->second, name(), "", speed);
                attrs.push_back(attr);
            }
            else if (it->first == EXIF_TAG_DATE_TIME_ORIGINAL) 
            {
                exif_entry_get_value(exifEntry, tag_data, 256);
                datetime = std::string(tag_data);
            }
            else if(it->first == EXIF_TAG_TIME_ZONE_OFFSET){
                exif_entry_get_value(exifEntry, tag_data, 256);
                timezone = atoi(tag_data);
            }
            else
            {   
                // Get the tag's data
                exif_entry_get_value(exifEntry, tag_data, 256);

                // Add tag data to blackboard
                TskBlackboardAttribute attr(it->second, name(), "", tag_data);
                attrs.push_back(attr);
            }
        }
        if(!datetime.empty()){
            Poco::DateTime parsedDT;
            int tzd;
            Poco::DateTimeParser::tryParse(datetime, parsedDT, tzd);
            if(timezone)
                parsedDT.makeUTC(timezone);
            else
                parsedDT.makeUTC(tzd);
            TskBlackboardAttribute attr(TSK_DATETIME, name(), "", (uint64_t)parsedDT.utcTime());
            attrs.push_back(attr);
        }
        if(attrs.size() > 0){
            TskBlackboardArtifact art = pFile->createArtifact(TSK_METADATA_EXIF);
            for(size_t i = 0; i < attrs.size(); i++){
                art.addAttribute(attrs[i]);
            }
        }
    }
示例#21
0
void SyslogParser::parseBSD(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos)
{
	Poco::Message::Priority prio = convert(severity);
	// rest of the unparsed header is:
	// "%b %f %H:%M:%S" SP hostname|ipaddress
	// detect three spaces
	int spaceCnt = 0;
	std::size_t start = pos;
	while (spaceCnt < 3 && pos < msg.size())
	{
		if (msg[pos] == ' ')
		{
			spaceCnt++;
			if (spaceCnt == 1)
			{
				// size must be 3 chars for month
				if (pos - start != 3)
				{
					// probably a shortened time value, or the hostname
					// assume hostName
					Poco::Message logEntry(msg.substr(start, pos-start), msg.substr(pos+1), prio);
					_pListener->log(logEntry);
					return;
				}
			}
			else if (spaceCnt == 2)
			{
				// a day value!
				if (!(std::isdigit(msg[pos-1]) && (std::isdigit(msg[pos-2]) || std::isspace(msg[pos-2]))))
				{
					// assume the next field is a hostname
					spaceCnt = 3;
				}
			}
			if (pos + 1 < msg.size() && msg[pos+1] == ' ')
			{
				// we have two spaces when the day value is smaller than 10!
				++pos; // skip one
			}
		}
		++pos;
	}
	std::string timeStr(msg.substr(start, pos-start-1));
	int tzd(0);
	Poco::DateTime date;
	int year = date.year(); // year is not included, use the current one
	bool hasDate = Poco::DateTimeParser::tryParse(RemoteSyslogChannel::BSD_TIMEFORMAT, timeStr, date, tzd);
	if (hasDate)
	{
		int m = date.month();
		int d = date.day();
		int h = date.hour();
		int min = date.minute();
		int sec = date.second();
		date = Poco::DateTime(year, m, d, h, min, sec);
	}
	// next entry is host SP
	std::string hostName(parseUntilSpace(msg, pos));

	// TAG: at most 32 alphanumeric chars, ANY non alphannumeric indicates start of message content
	// ignore: treat everything as content
	std::string message(msg.substr(pos));
	pos = msg.size();
	Poco::Message logEntry(hostName, message, prio);
	logEntry.setTime(date.timestamp());
	_pListener->log(logEntry);
}
示例#22
0
	void convert(const std::string& path)
	{
		Poco::Path p(path);
		Poco::Path op(path);
		if (_output.empty())
		{
			op.setExtension("cpsp");
		}
		else
		{
			op = _output;
		}
		if (_contentType.empty())
		{
			_contentType = extToContentType(p.getExtension());
		}
		if (_clazz.empty())
		{
			_clazz = p.getBaseName();
		}
		Poco::FileInputStream istr(path);
		Poco::FileOutputStream ostr(op.toString());
		ostr << "<%@ page\n"
		     << "    contentType=\"" << _contentType << "\"\n"
		     << "    form=\"false\"\n"
		     << "    namespace=\"" << _namespace << "\"\n"
		     << "    class=\"" << _clazz << "\"\n"
		     << "    precondition=\"checkModified(request)\"%><%@"
		     << "    impl include=\"Poco/DateTime.h\"\n"
		     << "         include=\"Poco/DateTimeParser.h\"\n"
		     << "         include=\"Poco/DateTimeFormatter.h\"\n"
		     << "         include=\"Poco/DateTimeFormat.h\"%><%!\n\n";
		ostr << "// " << path << "\n";
		ostr << "static const unsigned char data[] = {\n\t";
		int ch = istr.get();
		int pos = 0;
		while (ch != -1)
		{
			ostr << "0x" << NumberFormatter::formatHex(ch, 2) << ", ";
			if (pos++ == 16)
			{
				ostr << "\n\t";
				pos = 0;
			}
			ch = istr.get();
		}
		Poco::File f(path);
		Poco::DateTime lm = f.getLastModified();
		ostr << "\n};\n\n\n";
		ostr << "static bool checkModified(Poco::Net::HTTPServerRequest& request)\n"
		     << "{\n"
		     << "\tPoco::DateTime modified(" << lm.year() << ", " << lm.month() << ", " << lm.day() << ", " << lm.hour() << ", " << lm.minute() << ", " << lm.second() << ");\n"
		     << "\trequest.response().setChunkedTransferEncoding(false);\n"
		     << "\trequest.response().set(\"Last-Modified\", Poco::DateTimeFormatter::format(modified, Poco::DateTimeFormat::HTTP_FORMAT));\n"
		     << "\tif (request.has(\"If-Modified-Since\"))\n"
		     << "\t{\n"
		     << "\t\tPoco::DateTime modifiedSince;\n"
		     << "\t\tint tzd;\n"
		     << "\t\tPoco::DateTimeParser::parse(request.get(\"If-Modified-Since\"), modifiedSince, tzd);\n"
		     << "\t\tif (modified <= modifiedSince)\n"
		     << "\t\t{\n"
		     << "\t\t\trequest.response().setContentLength(0);\n"
		     << "\t\t\trequest.response().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);\n"
		     << "\t\t\trequest.response().send();\n"
		     << "\t\t\treturn false;\n"
		     << "\t\t}\n"
		     << "\t}\n"
		     << "\trequest.response().setContentLength(static_cast<int>(sizeof(data)));\n"
		     << "\treturn true;\n"
		     << "}\n"
			 << "%><%\n"
		     << "\tresponseStream.write(reinterpret_cast<const char*>(data), sizeof(data));\n"
		     << "%>";
	}
示例#23
0
void AppRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	// Check for the favicon.ico request, we don't have one for now,
	// so set status code to HTTP_NOT_FOUND
	if ( request.getURI().compare("/favicon.ico") == 0 )
	{
		response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		response.send();
		return;
	}

	std::string lastModifiedHeader = request.get("If-Modified-Since", "");

	Poco::URI uri(request.getURI());

	Poco::Util::Application& app = Poco::Util::Application::instance();
	std::string staticPathname = app.config().getString("mq.web.app", "");
	if ( staticPathname.empty() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error("mq.web.app property not defined. Check your configuration.");
		response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
		response.send();
		return;
	}

	Poco::Path staticPath(staticPathname);
	staticPath.makeDirectory();

	std::vector<std::string> uriPathSegments;
	uri.getPathSegments(uriPathSegments);
	std::vector<std::string>::iterator it = uriPathSegments.begin();
	it++;
	for(; it != uriPathSegments.end(); ++it)
	{
		staticPath.append(*it);
	}
	if (staticPath.isDirectory())
	{
		staticPath.append("index.html");
	}

	Poco::File staticFile(staticPath);

	Poco::Logger& logger = Poco::Logger::get("mq.web.access");
	if ( staticFile.exists() )
	{
		if ( !lastModifiedHeader.empty() )
		{
			Poco::DateTime lastModifiedDate;
			int timeZoneDifferential = 0;
			if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) )
			{
				if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() )
				{
					logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString()));
					response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
					response.send();
					return;
				}
			}
		}

		logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString()));

		std::string mimeType;
		if ( staticPath.getExtension().compare("gif") == 0 )
		{
			mimeType = "image/gif";
		}
		else if ( staticPath.getExtension().compare("css") == 0 )
		{
			mimeType = "text/css";
		}
		else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0)
		{
			mimeType = "text/html";
		}
		else if ( staticPath.getExtension().compare("js") == 0 )
		{
			mimeType = "text/javascript";
		}
		else if ( staticPath.getExtension().compare("png") == 0 )
		{
			mimeType = "image/png";
		}
		else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0)
		{
			mimeType = "image/jpeg";
		}

		try
		{
			response.sendFile(staticPath.toString(), mimeType);
		}
		catch(Poco::FileNotFoundException&)
		{
			// We can't get here normally ... but you never know :)
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, Poco::Logger::format("Can't find file $0", staticPath.toString()));
		}
		catch(Poco::OpenFileException&)
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, Poco::Logger::format("Can't open file $0", staticPath.toString()));
		}
		return;
	}

	logger.error(Poco::Logger::format("$0 : HTTP_NOT_FOUND", staticFile.path()));
	response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
	response.send();
}
示例#24
0
void CalendarWidget::draw()
{
    ofFill();
    ofSetColor(0, 200);

    ofDrawRectangle(_window);

    std::string formatStringHourMin = "%h:%M %A";
    std::string formatStringHour = "%h:%M";
    std::string formatStringHourMinSec = "%h:%M:%S %A";

    Poco::LocalDateTime minTime(_windowInterval.getStart());
    Poco::LocalDateTime maxTime(_windowInterval.getEnd());

    Poco::LocalDateTime startQuarter = Utils::ceiling(minTime, Poco::Timespan::MINUTES * 5);

    ofPushMatrix();
    ofTranslate(_window.getPosition());

    std::vector<Poco::Timestamp> hours = Utils::getInstances(startQuarter.utc().timestamp(),
                                                             maxTime.utc().timestamp(),
                                                             Period(Period::MINUTE, 5));

    std::vector<Poco::Timestamp>::const_iterator hourIter = hours.begin();

    while (hourIter != hours.end())
    {
        Poco::DateTime time = Poco::DateTime(*hourIter);

        int y = _window.getHeight() * _windowInterval.map(time.timestamp());

        int minute = time.minute();

        float alpha = ofMap(std::abs(_windowInterval.map(time.timestamp()) - 0.5), 0, .2, .25, 1, true);

        if (0 == minute)
        {
            ofSetColor(255, 80 * alpha);
            ofDrawLine(0, y, _window.getWidth(), y);
        }
        else if (0 == minute % 15)
        {
            ofSetColor(255, 255, 0, 80 * alpha);
            ofDrawLine(0, y, _window.getWidth(), y);
        }
        else
        {
            ofSetColor(127, 80 * alpha);
            ofDrawLine(0, y, _window.getWidth(), y);
        }

        std::string label = Utils::format(Poco::LocalDateTime(time), formatStringHourMinSec);

        int width = _font.stringWidth(label);
        int height = _font.stringHeight(label);

        if (y - height - 4 > 0)
        {
            _font.drawString(label, _window.getWidth() - width - 4, y - 4);
        }

        ++hourIter;
    }

    int y = _window.getHeight() * _windowInterval.map(_now);

    ofSetColor(255);
    ofDrawLine(0, y, _window.getWidth(), y);

    std::string label = Utils::format(Poco::LocalDateTime(_now), formatStringHourMinSec);

    int width = _font.stringWidth(label);

    _font.drawString(label, _window.getWidth() - width - 4, y - 4);

    std::sort(_currentEvents.begin(), _currentEvents.end());


    ICalendar::EventInstances::const_iterator iter = _currentEvents.begin();

    int x = 0;

    while (iter != _currentEvents.end())
    {
        const ICalendarEvent& event = (*iter).getEvent();
        const Interval& interval = (*iter).getInterval();

        if (_windowInterval.intersects(interval))
        {
            int y0 = _window.getHeight() * _windowInterval.map(interval.getStart());
            int y1 = _window.getHeight() * _windowInterval.map(interval.getEnd());

            ofFill();
            ofSetColor(255, 50);

            if (interval.contains(_now))
            {
                ofSetColor(255, 255, 0, 50);
            }
            else
            {
                ofSetColor(255, 50);
            }


            ofDrawRectRounded(x, y0, 80, y1 - y0, 5);

            ofNoFill();
            ofSetColor(127);
            ofDrawRectRounded(x, y0, 80, y1 - y0, 5);

            ofSetColor(255);
            ofDrawRectRounded(x-1, y0-1, 80+2, y1 - y0+2, 5);


            std::string startLabel = Utils::format(Poco::LocalDateTime(interval.getStart()), formatStringHour);
            std::string endLabel = Utils::format(Poco::LocalDateTime(interval.getEnd()), formatStringHour);

            ofFill();
            ofSetColor(255);
            _font.drawString(event.getSummary(), x + 5, y0 + 10);
            _font.drawString(startLabel,         x + 5, y0 + 20);
            _font.drawString(endLabel,           x + 5, y0 + 30);
            
            x+= 84;
            
            if (x > _window.getWidth() - 160) x = 0;
            
        }
        
        ++iter;
    }
    
    ofPopMatrix();
}
示例#25
0
文件: utils.cpp 项目: rmnzr/murmur
//--------------------------------------------------------------
Poco::DateTime nowLocal()
{
	Poco::DateTime nowLocal;
	nowLocal.makeLocal(Poco::Timezone::tzd());
	return nowLocal;
}
void ofApp::updateSunPosition(){
    Poco::DateTime now; //UTC
	ofLogVerbose() << "updating sun position :";
	ofLogVerbose() << now.day() << " " << now.month() << " " << now.year() << " " << now.hour() << " " << now.minute();

	cTime ctime;
	ctime.iYear = now.year();
	ctime.iMonth = now.month();
	ctime.iDay = now.day();
	ctime.dHours = now.hour(); //UTC
	ctime.dMinutes = now.minute();
	ctime.dSeconds = now.second();

	cLocation location;
	location.dLatitude = Manager.myCoordinates.getLatitude();
	location.dLongitude = Manager.myCoordinates.getLongitude();
	ofVec2f data = sunpos(ctime, location, &sunCalc);

    double angle = 15 * (ctime.dHours + ctime.dMinutes/60);  //convert time to angle
    sunCoordinates.x = ofMap(angle, 0, 360, 180, -180);      //map angle to longitude
	sunCoordinates.y =  -data.y *180/PI;	                 //inclination of earth - convert from rad to degrees and invert

	ofLogVerbose() << "sun coordinates: longitude " << sunCoordinates.x << " / latitude:" << sunCoordinates.y;
}
示例#27
0
void FileServerRequestHandler::handleRequest(const HTTPRequest& request, Poco::MemoryInputStream& message,
                                             const std::shared_ptr<StreamSocket>& socket)
{
    try
    {
        bool noCache = false;
#if ENABLE_DEBUG
        noCache = true;
#endif
        Poco::Net::HTTPResponse response;
        Poco::URI requestUri(request.getURI());
        LOG_TRC("Fileserver request: " << requestUri.toString());
        requestUri.normalize(); // avoid .'s and ..'s

        std::string path(requestUri.getPath());
        if (path.find("loleaflet/" LOOLWSD_VERSION_HASH "/") == std::string::npos)
        {
            LOG_WRN("client - server version mismatch, disabling browser cache.");
            noCache = true;
        }

        std::vector<std::string> requestSegments;
        requestUri.getPathSegments(requestSegments);
        const std::string relPath = getRequestPathname(request);
        // Is this a file we read at startup - if not; its not for serving.
        if (requestSegments.size() < 1 || FileHash.find(relPath) == FileHash.end())
            throw Poco::FileNotFoundException("Invalid URI request: [" + requestUri.toString() + "].");

        const auto& config = Application::instance().config();
        const std::string loleafletHtml = config.getString("loleaflet_html", "loleaflet.html");
        const std::string endPoint = requestSegments[requestSegments.size() - 1];
        if (endPoint == loleafletHtml)
        {
            preprocessFile(request, message, socket);
            return;
        }

        if (request.getMethod() == HTTPRequest::HTTP_GET)
        {
            if (endPoint == "admin.html" ||
                endPoint == "adminSettings.html" ||
                endPoint == "adminHistory.html" ||
                endPoint == "adminAnalytics.html")
            {
                preprocessAdminFile(request, socket);
                return;
            }

            if (endPoint == "admin-bundle.js" ||
                endPoint == "admin-localizations.js")
            {
                noCache = true;

                if (!LOOLWSD::AdminEnabled)
                    throw Poco::FileAccessDeniedException("Admin console disabled");

                if (!FileServerRequestHandler::isAdminLoggedIn(request, response))
                    throw Poco::Net::NotAuthenticatedException("Invalid admin login");

                // Ask UAs to block if they detect any XSS attempt
                response.add("X-XSS-Protection", "1; mode=block");
                // No referrer-policy
                response.add("Referrer-Policy", "no-referrer");
            }

            // Do we have an extension.
            const std::size_t extPoint = endPoint.find_last_of('.');
            if (extPoint == std::string::npos)
                throw Poco::FileNotFoundException("Invalid file.");

            const std::string fileType = endPoint.substr(extPoint + 1);
            std::string mimeType;
            if (fileType == "js")
                mimeType = "application/javascript";
            else if (fileType == "css")
                mimeType = "text/css";
            else if (fileType == "html")
                mimeType = "text/html";
            else if (fileType == "png")
                mimeType = "image/png";
            else if (fileType == "svg")
                mimeType = "image/svg+xml";
            else
                mimeType = "text/plain";

            auto it = request.find("If-None-Match");
            if (it != request.end())
            {
                // if ETags match avoid re-sending the file.
                if (!noCache && it->second == "\"" LOOLWSD_VERSION_HASH "\"")
                {
                    // TESTME: harder ... - do we even want ETag support ?
                    std::ostringstream oss;
                    Poco::DateTime now;
                    Poco::DateTime later(now.utcTime(), int64_t(1000)*1000 * 60 * 60 * 24 * 128);
                    oss << "HTTP/1.1 304 Not Modified\r\n"
                        << "Date: " << Poco::DateTimeFormatter::format(
                            now, Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
                        << "Expires: " << Poco::DateTimeFormatter::format(
                            later, Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
                        << "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
                        << "Cache-Control: max-age=11059200\r\n"
                        << "\r\n";
                    socket->send(oss.str());
                    socket->shutdown();
                    return;
                }
            }

            response.set("User-Agent", HTTP_AGENT_STRING);
            response.set("Date", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT));

            bool gzip = request.hasToken("Accept-Encoding", "gzip");
            const std::string *content;
#if ENABLE_DEBUG
            if (std::getenv("LOOL_SERVE_FROM_FS"))
            {
                // Useful to not serve from memory sometimes especially during loleaflet development
                // Avoids having to restart loolwsd everytime you make a change in loleaflet
                const std::string filePath = Poco::Path(LOOLWSD::FileServerRoot, relPath).absolute().toString();
                HttpHelper::sendFile(socket, filePath, mimeType, response, noCache);
                return;
            }
#endif
            if (gzip)
            {
                response.set("Content-Encoding", "gzip");
                content = getCompressedFile(relPath);
            }
            else
                content = getUncompressedFile(relPath);

            if (!noCache)
            {
                // 60 * 60 * 24 * 128 (days) = 11059200
                response.set("Cache-Control", "max-age=11059200");
                response.set("ETag", "\"" LOOLWSD_VERSION_HASH "\"");
            }
            response.setContentType(mimeType);
            response.add("X-Content-Type-Options", "nosniff");

            std::ostringstream oss;
            response.write(oss);
            const std::string header = oss.str();
            LOG_TRC("#" << socket->getFD() << ": Sending " <<
                    (!gzip ? "un":"") << "compressed : file [" << relPath << "]: " << header);
            socket->send(header);
            socket->send(*content);
        }
    }
    catch (const Poco::Net::NotAuthenticatedException& exc)
    {
        LOG_ERR("FileServerRequestHandler::NotAuthenticated: " << exc.displayText());
        sendError(401, request, socket, "", "", "WWW-authenticate: Basic realm=\"online\"\r\n");
    }
    catch (const Poco::FileAccessDeniedException& exc)
    {
        LOG_ERR("FileServerRequestHandler: " << exc.displayText());
        sendError(403, request, socket, "403 - Access denied!",
                  "You are unable to access");
    }
    catch (const Poco::FileNotFoundException& exc)
    {
        LOG_WRN("FileServerRequestHandler: " << exc.displayText());
        sendError(404, request, socket, "404 - file not found!",
                  "There seems to be a problem locating");
    }
}
示例#28
0
//----------------------------------------
//	DisplayDateTime
//----------------------------------------
void DisplayDateTime(const Poco::DateTime& dateTime, ScopedLogMessage& msg)
{
	msg.Message(Poco::format("            year = %d", dateTime.year()));
	msg.Message(Poco::format("           month = %d\t(1 to 12)", dateTime.month()));
	msg.Message(Poco::format("             day = %d\t(1 to 31)", dateTime.day()));
	msg.Message(Poco::format("            hour = %d\t(0 to 23)", dateTime.hour()));
	msg.Message(Poco::format("          minute = %d\t(0 to 59)", dateTime.minute()));
	msg.Message(Poco::format("          second = %d\t(0 to 59)", dateTime.second()));
	msg.Message(Poco::format("     millisecond = %d\t(0 to 999)", dateTime.millisecond()));
	msg.Message(Poco::format("     microsecond = %d\t(0 to 999)", dateTime.microsecond()));
	msg.Message(Poco::format("            isAM = %s\t(true or false)", std::string(dateTime.isAM() ? "true":"false")));
	msg.Message(Poco::format("            isPM = %s\t(true or false)", std::string(dateTime.isPM() ? "true":"false")));
	msg.Message(Poco::format("      isLeapYear = %s\t(true or false)", std::string(Poco::DateTime::isLeapYear(dateTime.year()) ? "true":"false")));
	msg.Message(Poco::format("        hourAMPM = %d\t(0 to 12)", dateTime.hourAMPM()));
	msg.Message(Poco::format("       dayOfWeek = %d\t(0 to 6,   0: Sunday)", dateTime.dayOfWeek()));
	msg.Message(Poco::format("       dayOfYear = %d\t(1 to 366, 1: January 1)", dateTime.dayOfYear()));
	msg.Message(Poco::format("     daysOfMonth = %d\t(1 to 366, 1: January 1)", Poco::DateTime::daysOfMonth(dateTime.year(), dateTime.month())));
	msg.Message(Poco::format("            week = %d\t(0 to 53,  1: the week containing January 4)", dateTime.week()));

	msg.Message("");
}
示例#29
0
void ClearHistory::run()
{
	UarcRmemdServer::GetLogger().information("ClearHistory Process is running!");
	//1.获取当前时间
	time_t thistime;
	thistime = time(NULL);
	std::string TimeChar = "";
	g_pClearHistory->TimeToChar(thistime, TimeChar);
	UarcRmemdServer::GetLogger().information("首次执行,当前时间为:%s", TimeChar);


	//2.计算下次清除时间
	int nClearTime = g_pClearHistory->nextClearTime(thistime);

	long int timedeff = 0;
	timedeff = nClearTime - (long int) thistime;
	Poco::DateTime dataTime;
	dataTime += timedeff*1000000;

	//加入清除队列
	g_pClearHistory->TimeToChar(nClearTime,TimeChar);
	ClearQueue.enqueueNotification(new ClearNotofication(nClearTime),dataTime.timestamp());
	UarcRmemdServer::GetLogger().information("首次执行,设置下次清除数据时间为:%s", TimeChar);
	printf("首次执行,设置下次清除数据时间为:%s\n", TimeChar.c_str());
	while (!_stopped)
	{

		//1.等待清除任务时刻的到来
		Poco::Notification::Ptr pNf(ClearQueue.waitDequeueNotification());
		if (_stopped)
		{
			return ;
		}
		if(pNf)
		{
			//ClearNotofication* pSNf = pNf.cast<ClearNotofication> ();
			//2先设置下次清除时间
			time_t thistime;
			thistime = time(NULL);
			std::string TimeChar = "";
			g_pClearHistory->TimeToChar(thistime, TimeChar);

			UarcRmemdServer::GetLogger().information("清除%s 时刻的定时任务",TimeChar);


			//3.计算下次清除时间
			int nClearTime = g_pClearHistory->nextClearTime(thistime);
			long int timedeff = 0;
			timedeff = nClearTime - (long int) thistime;
			Poco::DateTime dataTime;
			dataTime += timedeff*1000000;
			//4再加入清除队列
			g_pClearHistory->TimeToChar(nClearTime,TimeChar);
			ClearQueue.enqueueNotification(new ClearNotofication(nClearTime ),dataTime.timestamp());

			UarcRmemdServer::GetLogger().information("设置下次清除数据时间为:%s", TimeChar);
			//5此时执行清除处理
			Clearstwch.restart();
			bool bCleard = false;
			bCleard = _rdbmsClearHis->clearHisData();
			Clearstwch.stop();
			if (bCleard == true)
			{
			 UarcRmemdServer::GetLogger().information("清除历史数据成功,用时%d 秒",(int)Clearstwch.elapsedSeconds());
			}
			else
			{
				UarcRmemdServer::GetLogger().information("清除历史数据失败,用时%d 秒",(int)Clearstwch.elapsedSeconds());
				UarcRmemdServer::GetLogger().information("再次调用清除命令");
				bCleard = _rdbmsClearHis->clearHisData();
				if (bCleard == true)
				{
					UarcRmemdServer::GetLogger().information("再次清除历史数据并且成功被清除");
				}
				else
				{
					UarcRmemdServer::GetLogger().information("连续两次清除历史均失败");
				}
			}

		}
	}
	UarcRmemdServer::GetLogger().information("ClearHistory Process quit!", __FILE__,	__LINE__);
}