Exemple #1
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")));
		}
	}
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);
}
Exemple #4
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);
}
Exemple #5
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;
	}
}
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);
}
Exemple #7
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();
}
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();
}
Exemple #9
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__);
}