Exemplo n.º 1
0
void LocalPortForwarder::forward(Poco::Net::StreamSocket& socket)
{
	if (_logger.debug())
	{
		_logger.debug(Poco::format("Local connection accepted, creating forwarding connection to %s, remote port %hu", _remoteURI.toString(), _remotePort));
	}
	try
	{
		std::string path(_remoteURI.getPathEtc());
		if (path.empty()) path = "/";
		Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPRequest::HTTP_1_1);
		request.set(SEC_WEBSOCKET_PROTOCOL, WEBTUNNEL_PROTOCOL);
		request.set(X_WEBTUNNEL_REMOTEPORT, Poco::NumberFormatter::format(_remotePort));
		Poco::Net::HTTPResponse response;
		Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket = _pWebSocketFactory->createWebSocket(_remoteURI, request, response);
		if (response.get(SEC_WEBSOCKET_PROTOCOL, "") != WEBTUNNEL_PROTOCOL)
		{
			_logger.error("The remote host does not support the WebTunnel protocol.");
			pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
			pWebSocket->close();
			socket.close();
			return;
		}

		_pDispatcher->addSocket(socket, new StreamSocketToWebSocketForwarder(_pDispatcher, pWebSocket), _localTimeout);
		_pDispatcher->addSocket(*pWebSocket, new WebSocketToStreamSocketForwarder(_pDispatcher, socket), _remoteTimeout);
	}
	catch (Poco::Exception& exc)
	{
		_logger.error(Poco::format("Failed to open forwarding connection: %s", exc.displayText()));
		socket.close();
	}
}
Exemplo n.º 2
0
void MongoDBTest::testCursorRequest()
{
	Poco::MongoDB::Database db("team");
	Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertRequest = db.createInsertRequest("numbers");
	for(int i = 0; i < 10000; ++i)
	{
		Document::Ptr doc = new Document();
		doc->add("number", i);
		insertRequest->documents().push_back(doc);
	}
	_mongo->sendRequest(*insertRequest);

	Poco::Int64 count = db.count(*_mongo, "numbers");
	assert(count == 10000);

	Poco::MongoDB::Cursor cursor("team", "numbers");

	int n = 0;
	Poco::MongoDB::ResponseMessage& response = cursor.next(*_mongo);
	while(1)
	{
		n += response.documents().size();
		if ( response.cursorID() == 0 )
			break;
		response = cursor.next(*_mongo);
	}
	assert(n == 10000);

	Poco::MongoDB::QueryRequest drop("team.$cmd");
	drop.setNumberToReturn(1);
	drop.selector().add("drop", std::string("numbers"));

	Poco::MongoDB::ResponseMessage responseDrop;
	_mongo->sendRequest(drop, responseDrop);
}
Exemplo n.º 3
0
void WebEventServiceImpl::shutdownImpl(Poco::SharedPtr<Poco::Net::WebSocket> pWS, Poco::UInt16 statusCode, const std::string& statusMessage, bool passive)
{
    //_pContext->logger().notice("Shutting down WebSocket.");
    try
    {
        pWS->shutdown(statusCode, statusMessage);
    }
    catch (Poco::Exception& exc)
    {
        _pContext->logger().notice("Error while shutting down WebSocket: " + exc.displayText());
        passive = true; // don't wait for client confirmation
    }
    if (!passive)
    {
        if (pWS->poll(Poco::Timespan(WEBEVENT_SHUTDOWN_TIMEOUT, 0), Poco::Net::Socket::SELECT_READ))
        {
            Poco::Buffer<char> buffer(4096);
            int flags;
            pWS->receiveFrame(buffer.begin(), buffer.size(), flags);
            if (flags & Poco::Net::WebSocket::FRAME_OP_CLOSE)
            {
                pWS->close();
                return;
            }
        }
        _pContext->logger().notice("Client failed to confirm shutdown.");
    }
    pWS->close();
}
Exemplo n.º 4
0
Poco::SharedPtr<Poco::MongoDB::QueryRequest> Database::createCountRequest(const std::string& collectionName) const
{
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> request = createQueryRequest("$cmd");
	request->setNumberToReturn(1);
	request->selector().add("count", collectionName);
	return request;
}
Exemplo n.º 5
0
// SELECT DISTINCT birthyear FROM players WHERE birthyear > 1980
void sample10(Poco::MongoDB::Connection& connection)
{
	std::cout << "*** SAMPLE 10 ***" << std::endl;

	Poco::MongoDB::Database db("sample");
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = db.createCommand();

	command->selector()
		.add("distinct", "players")
		.add("key", "birthyear")
		.addNewDocument("query")
		.addNewDocument("birthyear")
		.add("$gt", 1980);

	Poco::MongoDB::ResponseMessage response;
	connection.sendRequest(*command, response);
	if ( response.hasDocuments() )
	{
		Poco::MongoDB::Array::Ptr values = response.documents()[0]->get<Poco::MongoDB::Array::Ptr>("values");
		for(int i = 0; i < values->size(); ++i )
		{
			std::cout << values->get<int>(i) << std::endl;
		}
	}

}
Exemplo n.º 6
0
void WebController::listener()
{
	Poco::SharedPtr<MultiView> multiView = new MultiView("base.tpl");
	multiView->add("head", new TemplateView("listener/head.tpl"));
	multiView->add("main", new TemplateView("listener/index.tpl"));
	setView(multiView);
}
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		try
		{			
			std::string proto = request.get("Sec-WebSocket-Protocol", "");
			Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket;
			if (proto == "com.appinf.webtunnel.server/1.0")
			{
				response.set("Sec-WebSocket-Protocol", proto);
				pWebSocket = new Poco::Net::WebSocket(request, response);
				_portReflector.addServerSocket(pWebSocket, "ac9667bb-6032-4267-af61-9a7aafd40479");
			}
			else if (proto == "com.appinf.webtunnel.client/1.0")
			{
				response.set("Sec-WebSocket-Protocol", proto);
				std::string portStr = request.get("X-WebTunnel-RemotePort", "");
				unsigned port;
				if (!portStr.empty() && Poco::NumberParser::tryParseUnsigned(portStr, port) && port > 0 && port < 65536)
				{
					pWebSocket = new Poco::Net::WebSocket(request, response);
					try
					{
						_portReflector.addClientSocket(pWebSocket, "ac9667bb-6032-4267-af61-9a7aafd40479", static_cast<Poco::UInt16>(port));
					}
					catch (Poco::NotFoundException&)
					{
						pWebSocket->shutdown(Poco::Net::WebSocket::WS_UNEXPECTED_CONDITION, "No connection to target available");
					}
				}
				else
				{
					pWebSocket = new Poco::Net::WebSocket(request, response);
					pWebSocket->shutdown(Poco::Net::WebSocket::WS_UNEXPECTED_CONDITION, "Missing or invalid X-WebTunnel-RemotePort header");
				}
			}
			else
			{
				pWebSocket = new Poco::Net::WebSocket(request, response);
				pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
			}
		}
		catch (WebSocketException& exc)
		{
			app.logger().log(exc);
			switch (exc.code())
			{
			case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
				response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
				// fallthrough
			case Poco::Net::WebSocket::WS_ERR_NO_HANDSHAKE:
			case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
			case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
				response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
				response.setContentLength(0);
				response.send();
				break;
			}
		}
	}
Exemplo n.º 8
0
void MessageConsumer::consume(MQHCONN conn, MQMD* md, MQGMO* gmo, MQBYTE* buffer, MQCBC* context)
{
	Poco::SharedPtr<Message> msg = new Message(buffer, context->DataLength);
	memcpy(msg->md(), md, sizeof(MQMD));

	MessageConsumer* consumer = reinterpret_cast<MessageConsumer*>(context->CallbackArea);
	consumer->message.notify(consumer, msg);
}
Exemplo n.º 9
0
void WebEventServiceImpl::addSubscriberImpl(Poco::SharedPtr<Poco::Net::WebSocket> pWS)
{
    Subscriber::Ptr pSubscriber = new Subscriber;
    pSubscriber->pWebSocket = pWS;
    _socketMap[*pWS] = pSubscriber;
    watchSocketImpl(*pWS);
    pWS->setSendTimeout(Poco::Timespan(WEBEVENT_SEND_TIMEOUT, 0));
    pWS->setReceiveTimeout(Poco::Timespan(WEBEVENT_RECEIVE_TIMEOUT, 0));
}
Exemplo n.º 10
0
Poco::Net::WebSocket* DefaultWebSocketFactory::createWebSocket(const Poco::URI& uri, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response)
{
	Poco::SharedPtr<Poco::Net::HTTPClientSession> pSession = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(uri);
	pSession->setTimeout(_timeout);
	if (!_username.empty())
	{
		Poco::Net::HTTPBasicCredentials creds(_username, _password);
		creds.authenticate(request);
	}
	return new Poco::Net::WebSocket(*pSession, request, response);
}
Exemplo n.º 11
0
//DELETE players WHERE firstname = 'Victor'
void sample13(Poco::MongoDB::Connection& connection)
{
	std::cout << "*** SAMPLE 13 ***" << std::endl;

	Poco::MongoDB::Database db("sample");
	Poco::SharedPtr<Poco::MongoDB::DeleteRequest> request = db.createDeleteRequest("players");
	request->selector().add("firstname", "Victor");

	connection.sendRequest(*request);

	Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(connection);
	std::cout << "LastError: " << lastError->toString(2) << std::endl;
}
bool MongoAuthentication::authenticateMongoCR(const std::string &user, const std::string &pwd)
{
	bool ret = false;
	_user = user;
	_pwd = pwd;

	try {
		std::string nonce;
		Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = _db.createCommand();
		command->selector().add<Poco::Int32>("getnonce", 1);
		command->setNumberToReturn(1);

		Poco::MongoDB::ResponseMessage response;
		_conn.sendRequest(*command, response);

		if (response.documents().size() > 0) {
			Poco::MongoDB::Document::Ptr doc = response.documents()[0];
			nonce = doc->get<std::string>("nonce", "");

			std::string password = _user + ":mongo:" + _pwd;

			Poco::MD5Engine md5;
			md5.update(password);
			std::string hashedPassword(Poco::DigestEngine::digestToHex(md5.digest()));
			std::string key = nonce + _user + hashedPassword;
			md5.reset();
			md5.update(key);
			std::string hashedKey(Poco::DigestEngine::digestToHex(md5.digest()));


			Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = _db.createCommand();
			command->selector()
				.add<Poco::Int32>("authenticate", 1)
				.add<std::string>("user", _user)
				.add<std::string>("nonce", nonce)
				.add<std::string>("key", hashedKey);      // hex_md5( n.nonce + username + hex_md5( username + ":mongo:" + password ) )

			_conn.sendRequest(*command, response);

			if (response.documents().size() > 0 && response.documents()[0]->get<double>("ok")) {
				ret = true;
			}
		}
	} catch (Poco::Exception &) {
		throw Poco::ApplicationException("auth failed.");
	}

	return ret;
}
Exemplo n.º 13
0
void CLogAnalyzerView::UpdateUISetting()
{
    if (!m_logger->GetActiveUISetting().isNull())
    {
        tstring strSettingName = m_logger->GetActiveUISetting()->getName();
        CLogAnalyzerApp* app = (CLogAnalyzerApp*)AfxGetApp();
        if (app != NULL)
        {
            Poco::SharedPtr<CUISetting> currentSelSetting = app->GetUISetting(strSettingName);
            if (!currentSelSetting.isNull())
                m_logger->SetActiveUISetting(currentSelSetting);
        }
    }
    
}
Exemplo n.º 14
0
void CLogAnalyzerView::ShowTraces(const CString& strComponent, BOOL bShowAll)
{
    tstring strItemText = strComponent;
    const std::map<tstring, Poco::SharedPtr<CComponent>>& components = m_logger->GetComponents();
    std::map<tstring, Poco::SharedPtr<CComponent>>::const_iterator ite = components.find(strItemText);
    if (ite != components.end())
    {
        const std::vector<Poco::SharedPtr<CTraceLog>>& traceLogs = ite->second->GetTraceLogs();
        if (bShowAll)
        {
            //Only show the traces you want in list control
            m_traceList.DeleteAllTraceLog();
            for (int i = 0; i < traceLogs.size(); ++i)
                m_traceList.InsertTraceLog(traceLogs.at(i));
        }
        //Show all traces and go to the first trace log that fits to you want
        else
        {
            Poco::SharedPtr<CUISetting> uiSetting = m_logger->GetActiveUISetting();
            int nColumn = 0;
            int nCurSel = m_comboColumns.GetCurSel();
            if (nCurSel == 0)
                nColumn = -1; //All
            else
            {
                CString strItem;
                m_comboColumns.GetLBText(nCurSel, strItem);
                tstring strItemValue = strItem.GetBuffer(strItem.GetLength());
                if (!uiSetting.isNull())
                {
                    for (int i = 0; i < uiSetting->GetAllColumns().size(); ++i)
                    {
                        if (strItemValue == uiSetting->GetAllColumns().at(i)->m_strRealColumnName)
                        {
                            nColumn = i;
                            break;
                        }
                    }
                }
            }

            m_traceList.SearchText(nColumn, m_strFindContent.GetBuffer(m_strFindContent.GetLength()), m_bMatchCase);
        }
        m_strCurrentPage.Format("%d", m_traceList.GetCurrentPage());
        m_strTraceCount.Format("Total : %d", m_traceList.GetCount());
        UpdateData(FALSE);
    }
}
Exemplo n.º 15
0
void MongoDBTest::testCursorRequest()
{
	if (!_connected)
	{
		std::cout << "Not connected, test skipped." << std::endl;
		return;
	}

	Poco::MongoDB::Database db("team");
	Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertRequest = db.createInsertRequest("numbers");
	for(int i = 0; i < 10000; ++i)
	{
		Document::Ptr doc = new Document();
		doc->add("number", i);
		insertRequest->documents().push_back(doc);
	}
	_mongo.sendRequest(*insertRequest);

	double count = db.count(_mongo, "numbers");
	assert(count == 10000);

	Poco::MongoDB::Cursor cursor("team", "numbers");

	int n = 0;
	Poco::MongoDB::ResponseMessage& response = cursor.next(_mongo);
	while(1)
	{
		n += response.documents().size();
		if ( response.cursorID() == 0 )
			break;
		response = cursor.next(_mongo);
	}
	std::cout << "n= " << n << std::endl;
	assert(n == 10000);

	Poco::MongoDB::QueryRequest drop("team.$cmd");
	drop.setNumberToReturn(1);
	drop.selector().add("drop", std::string("numbers"));

	Poco::MongoDB::ResponseMessage responseDrop;
	_mongo.sendRequest(drop, responseDrop);

	if ( responseDrop.documents().size() > 0 )
	{
		std::cout << responseDrop.documents()[0]->toString(2) << std::endl;
	}
}
Exemplo n.º 16
0
	void createGNSSSensor(Poco::SharedPtr<Poco::Serial::SerialPort> pSerialPort)
	{
		typedef Poco::RemotingNG::ServerHelper<IoT::Devices::GNSSSensor> ServerHelper;
		
		Poco::SharedPtr<GNSSSensorImpl> pGNSSSensor = new GNSSSensorImpl(pSerialPort);
		std::string type = pGNSSSensor->getPropertyString("type");
		Poco::RemotingNG::Identifiable::ObjectId oid = pGNSSSensor->getPropertyString("symbolicName");
		oid += "#0";
		ServerHelper::RemoteObjectPtr pGNSSSensorRemoteObject = ServerHelper::createRemoteObject(pGNSSSensor, oid);
		
		Properties props;
		props.set("io.macchina.deviceType", type);
		props.set("io.macchina.device", oid);
		props.set("io.macchina.serialport.device", pSerialPort->device());
		
		_serviceRef = _pContext->registry().registerService(oid, pGNSSSensorRemoteObject, props);
	}
Exemplo n.º 17
0
ConnectionBasePtr TransferNode::createConnection(const PacketBasePtr &packet_base, const EndPoint &ep) {
	PacketHeader::PACKET_ID_TYPE packet_id = packet_base->header.getPacketID();
	if (packet_id == OpenConnection_ID) {
		INFO_LOG("Server: new connection from: " << ep.toString());
		Poco::SharedPtr<OpenConnectionPacket> packet = packet_base.cast<OpenConnectionPacket>();
		assert(packet.get());
		ConnectionBasePtr pConn(new ServerConnection(packet->OpenConnection.Code, ep, this->packet_serializer, *this));
		return pConn;
	} else if (packet_id == OpenConnectionReply_ID) {
		INFO_LOG("Client: new connection to: " << ep.toString());
		Poco::SharedPtr<OpenConnectionReplyPacket> packet = packet_base.cast<OpenConnectionReplyPacket>();
		ConnectionBasePtr pConn(new ClientConnection(packet->OpenConnectionReply.Code, ep, this->packet_serializer, *this));
		return pConn;
	} else {
		throw Poco::ApplicationException("unexpected packet type: ", packet_base->header.getPacketID()); // TODO @@@ ???
	}
}
Exemplo n.º 18
0
	void createSerialDevice(const std::string& uid, SerialDeviceImpl::SerialPortPtr pSerialPort)
	{
		typedef Poco::RemotingNG::ServerHelper<IoT::Devices::SerialDevice> ServerHelper;
		
		Poco::SharedPtr<IoT::Devices::SerialDevice> pDevice = new SerialDeviceImpl(pSerialPort);
		std::string symbolicName = pDevice->getPropertyString("symbolicName");
		Poco::RemotingNG::Identifiable::ObjectId oid = symbolicName;
		oid += '#';
		oid += uid;
		ServerHelper::RemoteObjectPtr pDeviceRemoteObject = ServerHelper::createRemoteObject(pDevice, oid);
		
		Properties props;
		props.set("io.macchina.device", oid);
		props.set("io.macchina.serialport.device", pSerialPort->device());
		
		ServiceRef::Ptr pServiceRef = _pContext->registry().registerService(oid, pDeviceRemoteObject, props);
		_serviceRefs.push_back(pServiceRef);
	}
Exemplo n.º 19
0
Document::Ptr Database::getLastErrorDoc(Connection& connection) const
{
	Document::Ptr errorDoc;

	Poco::SharedPtr<Poco::MongoDB::QueryRequest> request = createQueryRequest("$cmd");
	request->setNumberToReturn(1);
	request->selector().add("getLastError", 1);

	Poco::MongoDB::ResponseMessage response;
	connection.sendRequest(*request, response);

	if ( response.documents().size() > 0 )
	{
		errorDoc = response.documents()[0];
	}

	return errorDoc;
}
Exemplo n.º 20
0
// SELECT COUNT(*) FROM players WHERE birthyear > 1980
void sample11(Poco::MongoDB::Connection& connection)
{
	std::cout << "*** SAMPLE 11 ***" << std::endl;

	Poco::MongoDB::Database db("sample");
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> count = db.createCountRequest("players");
	count->selector().addNewDocument("query")
		.addNewDocument("birthyear")
			.add("$gt", 1980);

	Poco::MongoDB::ResponseMessage response;
	connection.sendRequest(*count, response);

	if ( response.hasDocuments() )
	{
		std::cout << "Count: " << response.documents()[0]->get<double>("n") << std::endl;
	}
}
Exemplo n.º 21
0
void MongoDBTest::testDBQueryRequest()
{
	if (!_connected)
	{
		std::cout << "Not connected, test skipped." << std::endl;
		return;
	}

	Database db("team");
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> request = db.createQueryRequest("players");
	request->selector().add("lastname" , std::string("Braem"));

	Poco::MongoDB::ResponseMessage response;
	_mongo.sendRequest(*request, response);

	if ( response.documents().size() > 0 )
	{
		Poco::MongoDB::Document::Ptr doc = response.documents()[0];

		try
		{
			std::string lastname = doc->get<std::string>("lastname");
			assert(lastname.compare("Braem") == 0);
			std::string firstname = doc->get<std::string>("firstname");
			assert(firstname.compare("Franky") == 0);
			Poco::Timestamp birthDateTimestamp = doc->get<Poco::Timestamp>("birthdate");
			Poco::DateTime birthDate(birthDateTimestamp);
			assert(birthDate.year() == 1969 && birthDate.month() == 3 && birthDate.day() == 9);
			Poco::Timestamp lastupdatedTimestamp = doc->get<Poco::Timestamp>("lastupdated");
			assert(doc->isType<NullValue>("unknown"));

			std::string id = doc->get("_id")->toString();
			std::cout << id << std::endl;
		}
		catch(Poco::NotFoundException& nfe)
		{
			fail(nfe.message() + " not found.");
		}
	}
	else
	{
		fail("No document returned");
	}
}
Exemplo n.º 22
0
void MongoDBTest::testCommand() {
	Poco::MongoDB::Database db("team");
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = db.createCommand();
	command->selector().add("create", "fixCol")
		.add("capped", true)
		.add("max", 1024*1024)
		.add("size", 1024);

	Poco::MongoDB::ResponseMessage response;
	_mongo->sendRequest(*command, response);
	if ( response.documents().size() > 0 )
	{
		Poco::MongoDB::Document::Ptr doc = response.documents()[0];
	}
	else
	{
		Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(*_mongo);
		fail(lastError->toString(2));
	}
}
Exemplo n.º 23
0
QueueManager::Ptr QueueManagerPool::borrowObject()
{
	Poco::FastMutex::ScopedLock lock(_mutex);

	if (!_pool.empty())
	{
		Poco::SharedPtr<TimedQueueManager> pObject = _pool.back();
		_pool.pop_back();
		return activateObject(pObject->value());
	}

	if (_size < _peakCapacity)
	{
		QueueManager::Ptr pObject = _factory->createObject();
		activateObject(pObject);
		_size++;
		return pObject;
	}

	return 0;
}
Exemplo n.º 24
0
void WebEventServiceImpl::sendImpl(Poco::SharedPtr<Poco::Net::WebSocket> pWS, const std::string& message)
{
    try
    {
        pWS->sendFrame(message.data(), message.size());
    }
    catch (Poco::Exception& exc)
    {
        _pContext->logger().error("Error while sending frame: " + exc.displayText());
        removeSubscriber(pWS, false);
    }
}
Exemplo n.º 25
0
void WebController::message()
{
	std::vector<std::string> parameters = getParameters();
	if ( parameters.size() < 2 )
	{
		setResponseStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Missing URI parameters");
		return;
	}

	mqwebData().set("queue", parameters[1]);
	std::string messageId;
	if ( parameters.size() > 2 )
	{
		messageId = parameters[2];
		mqwebData().set("messageId", messageId);
	}

	Poco::SharedPtr<MultiView> multiView = new MultiView("base.tpl");
	multiView->add("head", new TemplateView("message/head.tpl"));
	multiView->add("main", new TemplateView("message/index.tpl"));
	setView(multiView);
}
Exemplo n.º 26
0
	bool handleFrame(Connection::Ptr pConnection, Frame::Ptr pFrame)
	{
		if (pFrame->type() == Frame::FRAME_TYPE_REQU && (pFrame->flags() & Frame::FRAME_FLAG_CONT) == 0)
		{
			Poco::SharedPtr<ChannelInputStream> pRequestStream = new ChannelInputStream(pConnection, pFrame->type(), pFrame->channel(), _pListener->getTimeout());
			Poco::SharedPtr<ChannelOutputStream> pReplyStream;
			if ((pFrame->flags() & Frame::FRAME_FLAG_ONEWAY) == 0)
			{
				Poco::UInt16 flags(0);
				if (pFrame->flags() & Frame::FRAME_FLAG_DEFLATE)
					flags |= Frame::FRAME_FLAG_DEFLATE;
				pReplyStream = new ChannelOutputStream(pConnection, Frame::FRAME_TYPE_REPL, pFrame->channel(), flags);
			}
			ServerTransport::Ptr pServerTransport = new ServerTransport(*_pListener, pRequestStream, pReplyStream, (pFrame->flags() & Frame::FRAME_FLAG_DEFLATE) != 0);
			_pListener->connectionManager().threadPool().start(*pServerTransport);
			Poco::Thread::yield();
			pServerTransport->waitReady();
			pRequestStream->rdbuf()->queue()->handleFrame(pConnection, pFrame);
			return true;
		}
		else return false;
	}
Exemplo n.º 27
0
int UarcRmemdServer::main(const std::vector<std::string>& args)
{

	if ( _helpRequested ) {

			displayHelp();

			return Application::EXIT_OK;
		}

	try {
		// laungh subsystems
		getSubsystem<ClearHistory> ().Start();
		getSubsystem<GatherSubsystem> ().Start();
		getSubsystem<CalcSubsystem> ().Start();
		getSubsystem<DataProcess> ().Start();
		getSubsystem<StoreExeSubsystem> ().Start();
		getSubsystem<WaitAllPerArchSubsystem> ().Start();




	} catch ( Poco::Exception& e ) {

			UarcRmemdServer::GetLogger().information(e.message(), __FILE__, __LINE__);
			return Application::EXIT_CANTCREAT;
		}

		// wait for CTRL-C or kill
		waitForTerminationRequest();
		g_pevtWakeup->set();

    getSubsystem<StoreExeSubsystem> ().Stop();
	printf("已经关闭归集指标处理线程!\n");
	getSubsystem<GatherSubsystem> ().Stop();
	printf("已经关闭归集回调任务线程!\n");
	getSubsystem<CalcSubsystem> ().Stop();
	printf("已经关闭计算任务线程!\n");
	getSubsystem<DataProcess> ().Stop();
	printf("已经关闭数据处理任务线程!\n");
	getSubsystem<WaitAllPerArchSubsystem> ().Stop();
	printf("已经关闭初始归集指标获取线程!\n");
	getSubsystem<ClearHistory> ().Stop();
	printf("已经关闭定时清除历史数据线程!\n");



		UarcRmemdServer::GetLogger().information("UarcRmemdServer quit.",	__FILE__, __LINE__);

		return Application::EXIT_OK;
}
Exemplo n.º 28
0
Poco::MongoDB::Document::Ptr Database::ensureIndex(Connection& connection, const std::string& collection, const std::string& indexName, Poco::MongoDB::Document::Ptr keys, bool unique, bool background, int version, int ttl)
{
	Poco::MongoDB::Document::Ptr index = new Poco::MongoDB::Document();
	index->add("ns", _dbname + ".players");
	index->add("name", indexName);
	index->add("key", keys);

	if ( version > 0 )
	{
		index->add("version", version);
	}

	if ( unique )
	{
		index->add("unique", true);
	}

	if ( background )
	{
		index->add("background", true);
	}

	if ( ttl > 0 )
	{
		index->add("expireAfterSeconds", ttl);
	}

	Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertRequest = createInsertRequest("system.indexes");
	insertRequest->documents().push_back(index);
	connection.sendRequest(*insertRequest);

	insertRequest->documents().push_back(index);
	connection.sendRequest(*insertRequest);

	return getLastErrorDoc(connection);
}
Exemplo n.º 29
0
// SELECT * FROM players LIMIT 1
void sample9(Poco::MongoDB::Connection& connection)
{
	std::cout << "*** SAMPLE 9 ***" << std::endl;

	// QueryRequest can be used directly
	Poco::MongoDB::QueryRequest query("sample.players");
	query.setNumberToReturn(1);
	Poco::MongoDB::ResponseMessage response;
	connection.sendRequest(query, response);
	if ( response.hasDocuments() )
	{
		std::cout << response.documents()[0]->toString(2) << std::endl;
	}

	// QueryRequest can be created using the Database class
	Poco::MongoDB::Database db("sample");
	Poco::SharedPtr<Poco::MongoDB::QueryRequest> queryPtr = db.createQueryRequest("players");
	queryPtr->setNumberToReturn(1);
	connection.sendRequest(*queryPtr, response);
	if ( response.hasDocuments() )
	{
		std::cout << response.documents()[0]->toString(2) << std::endl;
	}
}
Exemplo n.º 30
0
UarcRmemdServer::UarcRmemdServer() : _helpRequested(false) {
//地址需要改变
	int pid_file = ::open("/var/lock/uarc_rmemd.lock", O_CREAT | O_RDWR, 0666);
	int rc = flock(pid_file, LOCK_EX | LOCK_NB);
	if(rc) {
		std::cout << "UarcRmemdServer进程已存在,请不要重复运行!" << std::endl;
		exit(-1);
	}

	addSubsystem(new ClearHistory);
	addSubsystem(new GatherSubsystem);
	addSubsystem(new StoreExeSubsystem);
	addSubsystem(new CalcSubsystem);
	addSubsystem(new DataProcess);
	addSubsystem(new WaitAllPerArchSubsystem);



	g_pevtWakeup = new Poco::Event(false);
	g_pevtWakeup->reset();
}