void my::GateServer::handle_accept(ConnectionPtr conn, boost::system::error_code err) { if (err) { LogE << err.message() << LogEnd; conn->getSocket().close(); ConnectionPtr nextConn = boost::shared_ptr<TcpConnection>(new TcpConnection(core.getService(), m_GateHandler, shared_from_this())); m_pAcceptor->async_accept(nextConn->getSocket(), boost::bind(&GateServer::handle_accept, this, nextConn, boost::asio::placeholders::error)); } else { //new incomming player!!! LogD << conn->getSocket().remote_endpoint().address() << " " << conn->getSocket().remote_endpoint().port() << LogEnd; boost::recursive_mutex::scoped_lock lock(mtx); conn->setNetId(m_nNetIdHolder); ip::tcp::no_delay option(true); conn->getSocket().set_option(option); m_ConnMap.insert(std::make_pair<int, ConnectionPtr>(m_nNetIdHolder, conn)); conn->start(); m_nNetIdHolder = (m_nNetIdHolder + 1) % MAX_NET_ID; m_nConnCount++; ConnectionPtr nextConn = boost::shared_ptr<TcpConnection>(new TcpConnection(core.getService(), m_GateHandler, shared_from_this())); m_pAcceptor->async_accept(nextConn->getSocket(), boost::bind(&GateServer::handle_accept, this, nextConn, boost::asio::placeholders::error)); } }
CrowdDetectorFilterImpl::CrowdDetectorFilterImpl ( const std::vector<std::shared_ptr<RegionOfInterest>> &rois, std::shared_ptr< MediaObjectImpl > parent) : FilterImpl (parent) { GstBus *bus; std::shared_ptr<MediaPipelineImpl> pipe; GstStructure *roisStructure; pipe = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() ); g_object_set (element, "filter-factory", "crowddetector", NULL); bus = gst_pipeline_get_bus (GST_PIPELINE (pipe->getPipeline() ) ); g_object_get (G_OBJECT (element), "filter", &crowdDetector, NULL); if (crowdDetector == NULL) { g_object_unref (bus); throw KurentoException (MEDIA_OBJECT_NOT_AVAILABLE, "Media Object not available"); } roisStructure = gst_structure_new_empty ("Rois"); for (auto roi : rois) { GstStructure *roiStructureAux = get_structure_from_roi (roi); gst_structure_set (roisStructure, roi->getId().c_str(), GST_TYPE_STRUCTURE, roiStructureAux, NULL); gst_structure_free (roiStructureAux); } g_object_set (G_OBJECT (crowdDetector), ROIS_PARAM, roisStructure, NULL); gst_structure_free (roisStructure); busMessageLambda = [&] (GstMessage * message) { const GstStructure *st; gchar *roiID; const gchar *type; std::string roiIDStr, typeStr; if (GST_MESSAGE_SRC (message) != GST_OBJECT (crowdDetector) || GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT) { return; } st = gst_message_get_structure (message); type = gst_structure_get_name (st); if (!gst_structure_get (st, "roi", G_TYPE_STRING , &roiID, NULL) ) { GST_WARNING ("The message does not contain the roi ID"); return; } roiIDStr = roiID; typeStr = type; g_free (roiID); if (typeStr == "fluidity-event") { double fluidity_percentage; int fluidity_level; if (! (gst_structure_get (st, "fluidity_percentage", G_TYPE_DOUBLE, &fluidity_percentage, NULL) ) ) { GST_WARNING ("The message does not contain the fluidity percentage"); return; } if (! (gst_structure_get (st, "fluidity_level", G_TYPE_INT, &fluidity_level, NULL) ) ) { GST_WARNING ("The message does not contain the fluidity level"); return; } try { CrowdDetectorFluidity event (fluidity_percentage, fluidity_level, roiIDStr, shared_from_this(), CrowdDetectorFluidity::getName() ); signalCrowdDetectorFluidity (event); } catch (std::bad_weak_ptr &e) { } } else if (typeStr == "occupancy-event") { double occupancy_percentage; int occupancy_level; if (! (gst_structure_get (st, "occupancy_percentage", G_TYPE_DOUBLE, &occupancy_percentage, NULL) ) ) { GST_WARNING ("The message does not contain the occupancy percentage"); return; } if (! (gst_structure_get (st, "occupancy_level", G_TYPE_INT, &occupancy_level, NULL) ) ) { GST_WARNING ("The message does not contain the occupancy level"); return; } try { CrowdDetectorOccupancy event (occupancy_level, occupancy_percentage, roiIDStr, shared_from_this(), CrowdDetectorOccupancy::getName() ); signalCrowdDetectorOccupancy (event); } catch (std::bad_weak_ptr &e) { } } else if (typeStr == "direction-event") { double direction_angle; if (! (gst_structure_get (st, "direction_angle", G_TYPE_DOUBLE, &direction_angle, NULL) ) ) { GST_WARNING ("The message does not contain the direction angle"); return; } try { CrowdDetectorDirection event (direction_angle, roiIDStr, shared_from_this(), CrowdDetectorDirection::getName() ); signalCrowdDetectorDirection (event); } catch (std::bad_weak_ptr &e) { } } else { GST_WARNING ("The message does not have the correct name"); } }; bus_handler_id = g_signal_connect (bus, "message", G_CALLBACK (bus_message_adaptor), &busMessageLambda); g_object_unref (bus); // There is no need to reference crowddetector because its life cycle is the same as the filter life cycle g_object_unref (crowdDetector); }
void Node::forwardProperty(int ourProperty, std::shared_ptr<Node> toNode, int toProperty) { forwarded_properties[ourProperty] = std::make_tuple(toNode, toProperty); toNode->addPropertyBackref(toProperty, std::static_pointer_cast<Node>(shared_from_this()), ourProperty); simulation->invalidatePlan(); }
std::shared_ptr<base::IBlock> BlockFS::block() const { return std::const_pointer_cast<BlockFS>(shared_from_this()); }
neb::fnd::app::Base * const THIS::get_fnd_app() { auto a = std::dynamic_pointer_cast<neb::fnd::app::Base>(shared_from_this()); return a.get(); }
viewer::PluginPtr ModelLoaderPlugin::init(ViewerPtr viewer) { const std::string plugin_tkn("model_loader_plugin"); const std::string units_to_meters_tkn("units_to_meters"); const std::string position_tkn("position"); const std::string rotation_tkn("rotation"); const std::string models_tkn("models"); const std::string path_tkn("path"); const std::string grabbing_tkn("enable_grabbing"); const std::string core_type_tkn("core_type"); const unsigned int req_cfg_version(1); jccl::ConfigElementPtr elt = viewer->getConfiguration().getConfigElement(plugin_tkn); if ( !elt ) { std::stringstream ex_msg; ex_msg << "Model loader plug-in could not find its configuration. " << "Looking for type: " << plugin_tkn; throw PluginException(ex_msg.str(), VRKIT_LOCATION); } // -- Read configuration -- // vprASSERT(elt->getID() == plugin_tkn); // Check for correct version of plugin configuration if ( elt->getVersion() < req_cfg_version ) { std::stringstream msg; msg << "ModelLoaderPlugin: Configuration failed. Required cfg version: " << req_cfg_version << " found:" << elt->getVersion(); throw PluginException(msg.str(), VRKIT_LOCATION); } // Get the scaling factor const float to_meters = elt->getProperty<float>(units_to_meters_tkn); // Get the paths to all the models, load them, and add them to the scene ScenePtr scene = viewer->getSceneObj(); OSG::TransformNodePtr scene_xform_root = scene->getTransformRoot(); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor sxre(scene_xform_root.node(), OSG::Node::ChildrenFieldMask); #endif const unsigned int num_models(elt->getNum(models_tkn)); for ( unsigned int i = 0; i < num_models; ++i ) { jccl::ConfigElementPtr model_elt = elt->getProperty<jccl::ConfigElementPtr>(models_tkn, i); vprASSERT(model_elt.get() != NULL); const std::string model_path = model_elt->getProperty<std::string>(path_tkn); OSG::NodeRefPtr model_node( #if OSG_MAJOR_VERSION < 2 OSG::SceneFileHandler::the().read(model_path.c_str()) #else OSG::SceneFileHandler::the()->read(model_path.c_str()) #endif ); if ( model_node != OSG::NullFC ) { // Set up the model switch transform const float xt = model_elt->getProperty<float>(position_tkn, 0) * to_meters; const float yt = model_elt->getProperty<float>(position_tkn, 1) * to_meters; const float zt = model_elt->getProperty<float>(position_tkn, 2) * to_meters; const float xr = model_elt->getProperty<float>(rotation_tkn, 0); const float yr = model_elt->getProperty<float>(rotation_tkn, 1); const float zr = model_elt->getProperty<float>(rotation_tkn, 2); gmtl::Coord3fXYZ coord; coord.pos().set(xt,yt,zt); coord.rot().set(gmtl::Math::deg2Rad(xr), gmtl::Math::deg2Rad(yr), gmtl::Math::deg2Rad(zr)); // Set at T*R OSG::Matrix xform_mat_osg; gmtl::set(xform_mat_osg, gmtl::make<gmtl::Matrix44f>(coord)); OSG::NodeRefPtr child_root; // If this model is supposed to be grabbable, we create a vrkit // dynamic scene object for it. As a result, we can be assured // that the root node will have a core of type OSG::Transform. if ( model_elt->getProperty<bool>(grabbing_tkn) ) { std::vector<OSG::FieldContainerType*> core_types; const unsigned int num_types = model_elt->getNum(core_type_tkn); for ( unsigned int t = 0; t < num_types; ++t ) { const std::string type_name = model_elt->getProperty<std::string>(core_type_tkn, i); OSG::FieldContainerType* fct = OSG::FieldContainerFactory::the()->findType( type_name.c_str() ); if ( NULL != fct ) { core_types.push_back(fct); } else { VRKIT_STATUS << "Skipping unknown type '" << type_name << "'" << std::endl; } } DynamicSceneObjectPtr scene_obj; if ( ! core_types.empty() ) { util::CoreTypePredicate pred(core_types); scene_obj = DynamicSceneObject::create()->init(model_node, pred, true); } else { scene_obj = DynamicSceneObjectTransform::create()->init(model_node); } // scene_obj's root will be added as a child of // scene_xform_root. child_root = scene_obj->getRoot(); scene_obj->moveTo(xform_mat_osg); viewer->addObject(scene_obj); } // If this model is not supposed to be grabbable, we examine the // core of the root node. else { OSG::NodeCorePtr root_core = model_node->getCore(); OSG::TransformPtr xform_core = #if OSG_MAJOR_VERSION < 2 OSG::TransformPtr::dcast(root_core); #else OSG::cast_dynamic<OSG::TransformPtr>(root_core); #endif // If model_node's core is of type OSG::Transform, then we set // set the matrix on that core to be xform_mat_osg. if ( OSG::NullFC != xform_core ) { #if OSG_MAJOR_VERSION < 2 OSG::CPEditor xce(xform_core, OSG::Transform::MatrixFieldMask); #endif xform_core->setMatrix(xform_mat_osg); // model_node will be added as a child of scene_xform_root. child_root = model_node; } // If model_node's core is not of type OSG::Transform, then we // need to make a new node with an OSG::Transform core and make // it the parent of model_node. else { OSG::TransformNodePtr xform_node(OSG::Transform::create()); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor xnce(xform_node.core(), OSG::Transform::MatrixFieldMask); #endif xform_node->setMatrix(xform_mat_osg); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor xne(xform_node.node(), OSG::Node::ChildrenFieldMask); #endif xform_node.node()->addChild(model_node); // xform_node will be added as a child of scene_xform_root. child_root = xform_node.node(); } } vprASSERT(child_root != OSG::NullFC); // The OSG::{begin,end}EditCP() calls for scene_xform_root wrap // the for loop that we are in. scene_xform_root.node()->addChild(child_root); } } return shared_from_this(); }
bool Subscription::negotiateConnection(const std::string& xmlrpc_uri) { XmlRpcValue tcpros_array, protos_array, params; XmlRpcValue udpros_array; ros::TransportUDPPtr udp_transport; int protos = 0; ros::V_string transports = transport_hints_.getTransports(); if (transports.empty()) { transport_hints_.reliable(); transports = transport_hints_.getTransports(); } for (ros::V_string::const_iterator it = transports.begin(); it != transports.end(); ++it) { if (*it == "UDP") { int max_datagram_size = transport_hints_.getMaxDatagramSize(); udp_transport = ros::TransportUDPPtr(new ros::TransportUDP(&ros::PollManager::instance()->getPollSet())); if (!max_datagram_size) max_datagram_size = udp_transport->getMaxDatagramSize(); udp_transport->createIncoming(0, false); udpros_array[0] = "UDPROS"; M_string m; m["topic"] = getName(); m["md5sum"] = md5sum(); m["callerid"] = ros::this_node::getName(); m["type"] = datatype(); boost::shared_array<uint8_t> buffer; uint32_t len; ros::Header::write(m, buffer, len); XmlRpcValue v(buffer.get(), len); udpros_array[1] = v; udpros_array[2] = ros::network::getHost(); udpros_array[3] = udp_transport->getServerPort(); udpros_array[4] = max_datagram_size; protos_array[protos++] = udpros_array; } else if (*it == "TCP") { tcpros_array[0] = std::string("TCPROS"); protos_array[protos++] = tcpros_array; } else { ROS_WARN("Unsupported transport type hinted: %s, skipping", it->c_str()); } } params[0] = ros::this_node::getName(); params[1] = name_; params[2] = protos_array; std::string peer_host; uint32_t peer_port; if (!ros::network::splitURI(xmlrpc_uri, peer_host, peer_port)) { ROS_ERROR("Bad xml-rpc URI: [%s]", xmlrpc_uri.c_str()); return false; } XmlRpcClient* c = new XmlRpcClient(peer_host.c_str(), peer_port, "/"); // if (!c.execute("requestTopic", params, result) || !g_node->validateXmlrpcResponse("requestTopic", result, proto)) // Initiate the negotiation. We'll come back and check on it later. if (!c->executeNonBlock("requestTopic", params)) { ROSCPP_LOG_DEBUG("Failed to contact publisher [%s:%d] for topic [%s]", peer_host.c_str(), peer_port, name_.c_str()); delete c; if (udp_transport) { udp_transport->close(); } return false; } ROSCPP_LOG_DEBUG("Began asynchronous xmlrpc connection to [%s:%d]", peer_host.c_str(), peer_port); // The PendingConnectionPtr takes ownership of c, and will delete it on // destruction. PendingConnectionPtr conn(new PendingConnection(c, udp_transport, shared_from_this(), xmlrpc_uri)); //ROS_INFO("add connection to xmlrpcmanager"); XMLRPCManager::instance()->addASyncConnection(conn); // Put this connection on the list that we'll look at later. { boost::mutex::scoped_lock pending_connections_lock(pending_connections_mutex_); pending_connections_.insert(conn); } return true; }
CameraPtr Camera::init() { // Create a transform to contain the location and orientation of the camera. mTransform = OSG::Transform::create(); OSG::NodePtr beacon = OSG::Node::create(); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor be(beacon, OSG::Node::CoreFieldMask); #endif beacon->setCore(mTransform); mLeftTexture = tex_chunk_t::create(); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor lte(mLeftTexture); mLeftTexture->setEnvMode(GL_MODULATE); #else mLeftTexEnv = OSG::TextureEnvChunk::create(); mLeftTexEnv->setEnvMode(GL_MODULATE); #endif mRightTexture = tex_chunk_t::create(); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor rte(mRightTexture); mRightTexture->setEnvMode(GL_MODULATE); #else mRightTexEnv = OSG::TextureEnvChunk::create(); mRightTexEnv->setEnvMode(GL_MODULATE); #endif mCurrentTexture = mLeftTexture; #if OSG_MAJOR_VERSION >= 2 mCurrentTexEnv = mLeftTexEnv; #endif // setup camera mCamera = OSG::PerspectiveCamera::create(); #if OSG_MAJOR_VERSION < 2 OSG::CPEditor ce(mCamera); #endif mCamera->setFov( #if OSG_MAJOR_VERSION < 2 OSG::osgdegree2rad(60.0) #else OSG::osgDegree2Rad(60.0) #endif ); mCamera->setNear(0.01); mCamera->setFar(10000); mCamera->setBeacon(beacon); mLeftImage = OSG::Image::create(); mRightImage = OSG::Image::create(); OSG::ImagePtr img; // Set up FBO textures. img = mLeftImage; mLeftTexture->setMinFilter(GL_LINEAR); mLeftTexture->setMagFilter(GL_LINEAR); mLeftTexture->setTarget(GL_TEXTURE_2D); mLeftTexture->setInternalFormat(GL_RGBA8); mLeftTexture->setImage(img); img = mRightImage; mRightTexture->setMinFilter(GL_LINEAR); mRightTexture->setMagFilter(GL_LINEAR); mRightTexture->setTarget(GL_TEXTURE_2D); mRightTexture->setInternalFormat(GL_RGBA8); mRightTexture->setImage(img); mCurrentImage = mLeftImage; return shared_from_this(); }
void SuggestionsSidebarBlock::QueryProvider(SuggestionsBackend& backend, const CatalogItemPtr& item, uint64_t queryId) { m_pendingQueries++; // we need something to talk to GUI thread through that is guaranteed // to exist, and the app object is a good choice: auto backendPtr = &backend; std::weak_ptr<SuggestionsSidebarBlock> weakSelf = std::dynamic_pointer_cast<SuggestionsSidebarBlock>(shared_from_this()); m_provider->SuggestTranslation ( backend, m_parent->GetCurrentSourceLanguage(), m_parent->GetCurrentLanguage(), item->GetString().ToStdWstring(), // when receiving data [=](const SuggestionsList& hits){ call_on_main_thread([weakSelf,queryId,hits]{ auto self = weakSelf.lock(); // maybe this call is already out of date: if (!self || self->m_latestQueryId != queryId) return; self->UpdateSuggestions(hits); if (--self->m_pendingQueries == 0) self->OnQueriesFinished(); }); }, // on error: [=](std::exception_ptr e){ call_on_main_thread([weakSelf,queryId,backendPtr,e]{ auto self = weakSelf.lock(); // maybe this call is already out of date: if (!self || self->m_latestQueryId != queryId) return; self->ReportError(backendPtr, e); if (--self->m_pendingQueries == 0) self->OnQueriesFinished(); }); } ); }
void PlayListFolder::AddPlayList(boost::shared_ptr<PlayListElement> playList) { playList->SetParent(shared_from_this()); playlists_.push_back(playList); }
IDatabaseSPtr RedisServer::createDatabase(IDataBaseInfoSPtr info) { return IDatabaseSPtr(new RedisDatabase(shared_from_this(), info)); }
StructuredScript::Interfaces::Node::Ptr StructuredScript::Nodes::EchoNode::ptr(){ return shared_from_this(); }
void my::GateServer::connectToAccountSvr(std::string ipaddr, int port) { std::string portStr = boost::lexical_cast<std::string, int>(port); m_pAccountConn = boost::shared_ptr<TcpConnection>(new TcpConnection(core.getService(), m_GateHandler, shared_from_this())); m_pAccountConn->setNetId(my::server_id::ACCOUNT_SVR); connect(ipaddr, portStr, m_pAccountConn); }
void my::GateServer::init() { boost::shared_ptr<TcpServer> serverPtr(this); //make sure that shared_from_this() can run perfectly ok! Json::Value gateConf = util::fileSystem::loadJsonFileEval(jsonconf::server_config); if (gateConf == Json::nullValue) { LogW << "Error init GateServer, null gateConf" << LogEnd; return; } //初始化httpSvr { m_HttpServerPtr = HttpServerPtr(new http::HttpServer()); m_HttpServerPtr->init(gateConf); m_HttpServerPtr->run(); } m_GateConf = gateConf; int port = gateConf["gateSvrPort"].asInt(); std::string gameSvrIp = gateConf["gameSvrIp"].asString(); int gameSvrPort = gateConf["gameSvrPort"].asInt(); std::string accountSvrIp = gateConf["accountSvrIp"].asString(); int accountSvrPort = gateConf["accountSvrPort"].asInt(); m_nConnCount = 0; m_nNetIdHolder = 0; m_pEndpoint = EndpointPtr(new boost::asio::ip::tcp::endpoint(ip::tcp::v4(), port)); m_pAcceptor = AcceptorPtr(new boost::asio::ip::tcp::acceptor(core.getService(), *m_pEndpoint)); m_GateHandler = boost::shared_ptr<GateHandler>(new GateHandler()); ConnectionPtr nextConn = boost::shared_ptr<TcpConnection>(new TcpConnection(core.getService(), m_GateHandler, shared_from_this())); m_pAcceptor->async_accept(nextConn->getSocket(), boost::bind(&GateServer::handle_accept, this, nextConn, boost::asio::placeholders::error)); connectToGameSvr(gameSvrIp, gameSvrPort); connectToAccountSvr(accountSvrIp, accountSvrPort); LogD << "Init Gate Server Ok!!!" << LogEnd; update(); }
void CShips::Retreat(const CPoint& ptRetreatSector, COMBAT_TACTIC::Typ const* NewCombatTactic) { NotifySector temp(shared_from_this()); CShip::Retreat(ptRetreatSector, NewCombatTactic); }
void Player::collidedBy(std::shared_ptr<Actor> a) { a->collideWith(std::static_pointer_cast<Player>(shared_from_this())); }
sf::Vector2f CBaseControl::ConvertPointToControl(const sf::Vector2f & pt, const CBaseControlConstPtr & control) const { return control->ConvertPointFromControl(pt, shared_from_this()); }
void UIWidget::RequestFocus(){ auto p = parent.lock(); if(!p) return; p->OnChildFocusRequested(shared_from_this()); }
void Connection::parsePacket(const boost::system::error_code& error) { m_connectionLock.lock(); m_readTimer.cancel(); if (error) { handleReadError(error); } if (m_connectionState != CONNECTION_STATE_OPEN || m_readError) { closeConnection(); m_connectionLock.unlock(); return; } uint32_t timePassed = std::max<uint32_t>(1, (time(nullptr) - m_timeConnected) + 1); if ((++m_packetsSent / timePassed) > (uint32_t)g_config.getNumber(ConfigManager::MAX_PACKETS_PER_SECOND)) { std::cout << convertIPToString(getIP()) << " disconnected for exceeding packet per second limit." << std::endl; closeConnection(); m_connectionLock.unlock(); return; } if (timePassed > 2) { m_timeConnected = time(nullptr); m_packetsSent = 0; } //Check packet checksum uint32_t checksum; int32_t len = m_msg.getMessageLength() - m_msg.getReadPos() - 4; if (len > 0) { checksum = adlerChecksum(m_msg.getBuffer() + m_msg.getReadPos() + 4, len); } else { checksum = 0; } uint32_t recvChecksum = m_msg.get<uint32_t>(); if (recvChecksum != checksum) { // it might not have been the checksum, step back m_msg.SkipBytes(-4); } if (!m_receivedFirst) { // First message received m_receivedFirst = true; if (!m_protocol) { // Game protocol has already been created at this point m_protocol = m_service_port->make_protocol(recvChecksum == checksum, m_msg); if (!m_protocol) { closeConnection(); m_connectionLock.unlock(); return; } m_protocol->setConnection(shared_from_this()); } else { m_msg.GetByte(); // Skip protocol ID } m_protocol->onRecvFirstMessage(m_msg); } else { m_protocol->onRecvMessage(m_msg); // Send the packet to the current protocol } try { m_readTimer.expires_from_now(boost::posix_time::seconds(Connection::read_timeout)); m_readTimer.async_wait( std::bind(&Connection::handleReadTimeout, std::weak_ptr<Connection>(shared_from_this()), std::placeholders::_1)); // Wait to the next packet boost::asio::async_read(getHandle(), boost::asio::buffer(m_msg.getBuffer(), NetworkMessage::header_length), std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1)); } catch (boost::system::system_error& e) { if (m_logError) { std::cout << "[Network error - Connection::parsePacket] " << e.what() << std::endl; m_logError = false; } closeConnection(); } m_connectionLock.unlock(); }
bool UIWidget::IsFocused() const{ auto p = parent.lock(); if(!p) return IsRoot(); // Root widgets are always focused, but parentless widgets never. return p->OnChildFocusTested(shared_from_this()); }
void Subscription::pendingConnectionDone(const PendingConnectionPtr& conn, XmlRpcValue& result) { boost::mutex::scoped_lock lock(shutdown_mutex_); if (shutting_down_ || dropped_) { return; } { boost::mutex::scoped_lock pending_connections_lock(pending_connections_mutex_); pending_connections_.erase(conn); } ros::TransportUDPPtr udp_transport; std::string peer_host = conn->getClient()->getHost(); uint32_t peer_port = conn->getClient()->getPort(); std::stringstream ss; ss << "http://" << peer_host << ":" << peer_port << "/"; std::string xmlrpc_uri = ss.str(); udp_transport = conn->getUDPTransport(); XmlRpc::XmlRpcValue proto; if(!XMLRPCManager::instance()->validateXmlrpcResponse("requestTopic", result, proto)) { ROSCPP_LOG_DEBUG("Failed to contact publisher [%s:%d] for topic [%s]", peer_host.c_str(), peer_port, name_.c_str()); closeTransport(udp_transport); return; } if (proto.size() == 0) { ROSCPP_LOG_DEBUG("Couldn't agree on any common protocols with [%s] for topic [%s]", xmlrpc_uri.c_str(), name_.c_str()); closeTransport(udp_transport); return; } if (proto.getType() != XmlRpcValue::TypeArray) { ROSCPP_LOG_DEBUG("Available protocol info returned from %s is not a list.", xmlrpc_uri.c_str()); closeTransport(udp_transport); return; } if (proto[0].getType() != XmlRpcValue::TypeString) { ROSCPP_LOG_DEBUG("Available protocol info list doesn't have a string as its first element."); closeTransport(udp_transport); return; } std::string proto_name = proto[0]; if (proto_name == "TCPROS") { if (proto.size() != 3 || proto[1].getType() != XmlRpcValue::TypeString || proto[2].getType() != XmlRpcValue::TypeInt) { ROSCPP_LOG_DEBUG("publisher implements TCPROS, but the " \ "parameters aren't string,int"); return; } std::string pub_host = proto[1]; int pub_port = proto[2]; ROSCPP_LOG_DEBUG("Connecting via tcpros to topic [%s] at host [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port); //ROS_INFO("here in subscription"); //ros::TransportTCPPtr transport(new ros::TransportTCP(&ros::PollManager::instance()->getPollSet())); ros::TransportTCPPtr transport(new ros::TransportTCP(&poll_manager_->getPollSet())); if (transport->connect(pub_host, pub_port)) { ros::ConnectionPtr connection(new ros::Connection()); TransportPublisherLinkPtr pub_link(new TransportPublisherLink(shared_from_this(), xmlrpc_uri, transport_hints_)); connection->initialize(transport, false, ros::HeaderReceivedFunc()); pub_link->initialize(connection); ConnectionManager::instance()->addConnection(connection); boost::mutex::scoped_lock lock(publisher_links_mutex_); addPublisherLink(pub_link); ROSCPP_LOG_DEBUG("Connected to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port); } else { ROSCPP_LOG_DEBUG("Failed to connect to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port); } } else if (proto_name == "UDPROS") { if (proto.size() != 6 || proto[1].getType() != XmlRpcValue::TypeString || proto[2].getType() != XmlRpcValue::TypeInt || proto[3].getType() != XmlRpcValue::TypeInt || proto[4].getType() != XmlRpcValue::TypeInt || proto[5].getType() != XmlRpcValue::TypeBase64) { ROSCPP_LOG_DEBUG("publisher implements UDPROS, but the " \ "parameters aren't string,int,int,int,base64"); closeTransport(udp_transport); return; } std::string pub_host = proto[1]; int pub_port = proto[2]; int conn_id = proto[3]; int max_datagram_size = proto[4]; std::vector<char> header_bytes = proto[5]; boost::shared_array<uint8_t> buffer = boost::shared_array<uint8_t>(new uint8_t[header_bytes.size()]); memcpy(buffer.get(), &header_bytes[0], header_bytes.size()); ros::Header h; std::string err; if (!h.parse(buffer, header_bytes.size(), err)) { ROSCPP_LOG_DEBUG("Unable to parse UDPROS connection header: %s", err.c_str()); closeTransport(udp_transport); return; } ROSCPP_LOG_DEBUG("Connecting via udpros to topic [%s] at host [%s:%d] connection id [%08x] max_datagram_size [%d]", name_.c_str(), pub_host.c_str(), pub_port, conn_id, max_datagram_size); std::string error_msg; if (h.getValue("error", error_msg)) { ROSCPP_LOG_DEBUG("Received error message in header for connection to [%s]: [%s]", xmlrpc_uri.c_str(), error_msg.c_str()); closeTransport(udp_transport); return; } TransportPublisherLinkPtr pub_link(new TransportPublisherLink(shared_from_this(), xmlrpc_uri, transport_hints_)); if (pub_link->setHeader(h)) { ros::ConnectionPtr connection(new ros::Connection()); connection->initialize(udp_transport, false, NULL); connection->setHeader(h); pub_link->initialize(connection); ConnectionManager::instance()->addConnection(connection); boost::mutex::scoped_lock lock(publisher_links_mutex_); addPublisherLink(pub_link); ROSCPP_LOG_DEBUG("Connected to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port); } else { ROSCPP_LOG_DEBUG("Failed to connect to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port); closeTransport(udp_transport); return; } } else { ROSCPP_LOG_DEBUG("Publisher offered unsupported transport [%s]", proto_name.c_str()); } }
bool UIWidget::IsRoot() const{ auto w = window.lock(); if(!w) return false; return w->GetRoot() == shared_from_this(); }
void TransportPublisherLink::handleMessage(const SerializedMessage& m, bool ser, bool nocopy) { stats_.bytes_received_ += m.num_bytes; stats_.messages_received_++; SubscriptionPtr parent = parent_.lock(); if (parent) { stats_.drops_ += parent->handleMessage(m, ser, nocopy, getConnection()->getHeader().getValues(), shared_from_this()); } }
void ValueBindings::add(const ValueBindingPtr& var) { valueBindings.push_back(var); var->owner = std::static_pointer_cast<ValueBindings>(shared_from_this()); }
bool Join(Map& map) { return map.insert(Map::value_type(GetIndex(), shared_from_this())).second; }
void recruit::accept(visitor& v) { v.visit(shared_from_this()); }
void downloader_instance_simple2::handle_read(const boost::system::error_code& ec, std::size_t length) { if (!ec) { ostream_.write(buffer_, length); readed_bytes_ += length; if (owner()->progress_notify_) owner()->progress_notify_(readed_bytes_); { boost::mutex::scoped_lock lock(owner()->stateGuard_); while (owner()->command_ != http_downloader_simple2::commandNull) { switch (owner()->command_) { case http_downloader_simple2::commandPause: { owner()->state_ = http_downloader_simple2::statePaused; owner()->command_ = http_downloader_simple2::commandNull; if (owner()->state_notify_) owner()->state_notify_(http_downloader::statePause); while ( owner()->command_ != http_downloader_simple2::commandCancel && owner()->command_ != http_downloader_simple2::commandResume ) { lock.unlock(); boost::this_thread::sleep( boost::posix_time::milliseconds(100) ); lock.lock(); } if (owner()->command_ == http_downloader_simple2::commandResume) { owner()->state_ = http_downloader_simple2::stateDownload; owner()->command_ = http_downloader_simple2::commandNull; if (owner()->state_notify_) owner()->state_notify_(http_downloader::stateResume); } } break; case http_downloader_simple2::commandCancel: { owner()->command_ = http_downloader_simple2::commandNull; if (owner()->state_notify_) owner()->state_notify_(http_downloader::stateCancel); return; } break; case http_downloader_simple2::commandResume: break; } } } read_stream_.async_read_some( boost::asio::buffer(buffer_), boost::bind(&downloader_instance_simple2::handle_read, shared_from_this(), _1, _2)); } else { if ( boost::asio::error::misc_category == ec.category() ) { if (boost::asio::error::eof == ec.value()) { if (owner()->state_notify_) owner()->state_notify_(http_downloader::stateFinish); } } else { if (owner()->state_notify_) owner()->state_notify_(http_downloader::stateError); } } }
void TileObject::setPosition(Vec3<float> newPosition) { auto thisPtr = shared_from_this(); if (!thisPtr) { LogError("This == null"); } if (newPosition.x < 0 || newPosition.y < 0 || newPosition.z < 0 || newPosition.x > map.size.x + 1 || newPosition.y > map.size.y + 1 || newPosition.z > map.size.z + 1) { LogWarning("Trying to place object at {%f,%f,%f} in map of size {%d,%d,%d}", newPosition.x, newPosition.y, newPosition.z, map.size.x, map.size.y, map.size.z); newPosition.x = clamp(newPosition.x, 0.0f, (float)map.size.x + 1); newPosition.y = clamp(newPosition.y, 0.0f, (float)map.size.y + 1); newPosition.z = clamp(newPosition.z, 0.0f, (float)map.size.z + 1); LogWarning("Clamped object to {%f,%f,%f}", newPosition.x, newPosition.y, newPosition.z); } this->removeFromMap(); this->owningTile = map.getTile(newPosition); if (!this->owningTile) { LogError("Failed to get tile for position {%f,%f,%f}", newPosition.x, newPosition.y, newPosition.z); } auto inserted = this->owningTile->ownedObjects.insert(thisPtr); if (!inserted.second) { LogError("Object already in owned object list?"); } int layer = map.getLayer(this->type); this->owningTile->drawnObjects[layer].push_back(thisPtr); std::sort(this->owningTile->drawnObjects[layer].begin(), this->owningTile->drawnObjects[layer].end(), TileObjectZComparer{}); Vec3<int> minBounds = {floorf(newPosition.x - this->bounds.x / 2.0f), floorf(newPosition.y - this->bounds.y / 2.0f), floorf(newPosition.z - this->bounds.z / 2.0f)}; Vec3<int> maxBounds = {ceilf(newPosition.x + this->bounds.x / 2.0f), ceilf(newPosition.y + this->bounds.y / 2.0f), ceilf(newPosition.z + this->bounds.z / 2.0f)}; for (int x = minBounds.x; x < maxBounds.x; x++) { for (int y = minBounds.y; y < maxBounds.y; y++) { for (int z = minBounds.z; z < maxBounds.z; z++) { if (x < 0 || y < 0 || z < 0 || x > map.size.x || y > map.size.y || z > map.size.z) { // TODO: Decide if having bounds outside the map are really valid? continue; } Tile *intersectingTile = map.getTile(x, y, z); if (!intersectingTile) { LogError("Failed to get intersecting tile at {%d,%d,%d}", x, y, z); continue; } this->intersectingTiles.push_back(intersectingTile); intersectingTile->intersectingObjects.insert(thisPtr); } } } // Quick sanity check for (auto *t : this->intersectingTiles) { if (t->intersectingObjects.find(shared_from_this()) == t->intersectingObjects.end()) { LogError("Intersecting objects inconsistent"); } } }
void proxy::req_get::on_request(const ioremap::thevoid::http_request &req, const boost::asio::const_buffer &buffer) { HANDY_TIMER_START("mds.get.time", reinterpret_cast<uint64_t>(this)); HANDY_MDS_GET(); m_beg_time = std::chrono::system_clock::now(); url_str = req.url().path(); BH_LOG(logger(), SWARM_LOG_INFO, "Get: handle request: %s", url_str.c_str()); namespace_ptr_t ns; try { ns = server()->get_namespace(url_str, "/get"); auto &&prep_session = server()->prepare_session(url_str, ns); m_session = prep_session.first; m_session->set_timeout(server()->timeout.read); m_key = prep_session.second; m_key.transform(*m_session); m_key.set_id(m_key.id()); } catch (const std::exception &ex) { BH_LOG(logger(), SWARM_LOG_INFO, "Get: request = \"%s\"; err: \"%s\"", req.url().path().c_str(), ex.what()); HANDY_MDS_GET_REPLY(400); send_reply(400); return; } if (!server()->check_basic_auth(ns->name, ns->auth_key_for_read, req.headers().get("Authorization"))) { auto token = server()->get_auth_token(req.headers().get("Authorization")); BH_LOG(logger(), SWARM_LOG_INFO, "%s: invalid token \"%s\"" , url_str.c_str(), token.empty() ? "<none>" : token.c_str()); ioremap::thevoid::http_response reply; ioremap::swarm::http_headers headers; reply.set_code(401); headers.add("WWW-Authenticate", std::string("Basic realm=\"") + ns->name + "\""); headers.add("Content-Length", "0"); reply.set_headers(headers); HANDY_MDS_GET_REPLY(reply.code()); send_reply(std::move(reply)); return; } if (m_session->get_groups().empty()) { BH_LOG(logger(), SWARM_LOG_INFO , "Get %s: on_request: cannot find couple of groups for the request" , url_str.c_str()); HANDY_MDS_GET_REPLY(404); send_reply(404); return; } auto query_list = req.url().query(); m_offset = get_arg<uint64_t>(query_list, "offset", 0); m_size = get_arg<uint64_t>(query_list, "size", 0); m_if_modified_since = req.headers().get("If-Modified-Since"); m_first_chunk = true; m_chunk_size = server()->m_read_chunk_size; { std::ostringstream oss; oss << "Get " << m_key.remote() << " " << m_key.to_string() << ": lookup from groups ["; const auto &groups = m_session->get_groups(); for (auto bit = groups.begin(), it = bit, end = groups.end(); it != end; ++it) { if (it != bit) oss << ", "; oss << *it; } oss << ']'; auto msg = oss.str(); BH_LOG(logger(), SWARM_LOG_INFO, "%s", msg.c_str()); } { auto ioflags = m_session->get_ioflags(); m_session->set_ioflags(ioflags | DNET_IO_FLAGS_NOCSUM); m_session->set_timeout(server()->timeout.lookup); m_session->set_filter(ioremap::elliptics::filters::positive); auto alr = m_session->quorum_lookup(m_key); alr.connect(wrap(std::bind(&proxy::req_get::on_lookup, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); m_session->set_ioflags(ioflags); } }
void au::SessionTokenTestConnection::ParseHeaders( const std::size_t bytes_transferred ) { const std::string raw_headers([this, bytes_transferred] { asio::streambuf::const_buffers_type bufs = request_->read_buffer_.data(); return std::string( asio::buffers_begin(bufs), ( asio::buffers_begin(bufs) + bytes_transferred ) ); }()); std::string line; uint64_t content_length = 0; std::istream response_stream(&request_->read_buffer_); response_stream >> request_->http_method; response_stream >> request_->http_request_path; response_stream >> request_->http_version; std::getline(response_stream, line); if ( ! response_stream || request_->http_version.substr(0, 5) != "HTTP/") { std::cout << "Bad HTTP header." << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } std::string last_header_name; while (std::getline(response_stream, line) && line != "\r") { boost::trim_right(line); if ( line.empty() ) continue; // HTTP headers can be split up inbetween lines. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 if ( line[0] == ' ' || line[0] == '\t' ) { if ( last_header_name.empty() ) { std::cout << "Bad headers." << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } // This is a continuation of previous line. auto it = request_->headers.find(last_header_name); it->second += " "; boost::trim(line); it->second += line; continue; } boost::iterator_range<std::string::iterator> result = boost::find_first(line, ":"); if ( ! result.empty() ) { std::string header_name = std::string( line.begin(), result.begin()); std::string header_value = std::string( result.end(), line.end()); boost::trim(header_name); boost::to_lower(header_name); boost::trim(header_value); request_->headers.emplace(header_name, header_value); // Record the last header name in case the next line is // extended. last_header_name.swap(header_name); } } { auto it = request_->headers.find("content-length"); if ( it != request_->headers.end() ) { try { content_length = boost::lexical_cast<uint64_t>( it->second); } catch(boost::bad_lexical_cast &) { std::cout << "Invalid content length." << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } } } std::vector<std::string> request_path_parts; boost::split( request_path_parts, request_->http_request_path, boost::is_any_of("?")); if ( request_path_parts.size() > 2 ) { std::cout << "Bad request path: " << request_->http_request_path << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } request_->path = request_path_parts[0]; auto handler_it = handlers_->find( request_->path ); if ( handler_it == handlers_->end() ) { std::cout << "Server error: no handler for path: " << request_->path << std::endl; request_->Fail(HttpStatusCode::not_found); return; } if ( request_path_parts.size() > 1 ) { request_->query = request_path_parts[1]; std::vector<std::string> query_parts; boost::split( query_parts, request_->query, boost::is_any_of("&")); for ( const std::string & part : query_parts ) { std::vector<std::string> key_pair; boost::split( key_pair, part, boost::is_any_of("=")); boost::optional<std::string> key = get_parameter::Decode( key_pair[0] ); if ( ! key ) { std::cout << "Got bad url data." << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } if (key_pair.size() > 1) { boost::optional<std::string> value = get_parameter::Decode( key_pair[1] ); if ( ! value ) { std::cout << "Got bad url data." << std::endl; request_->Fail(HttpStatusCode::bad_request); return; } request_->query_parts[*key] = *value; } else request_->query_parts[*key] = ""; } } if ( content_length > 0 ) { auto self(shared_from_this()); // Empty buffer for reuse request_->read_buffer_.consume( request_->read_buffer_.size() ); asio::async_read( request_->ssl_stream, request_->read_buffer_, asio::transfer_exactly(content_length), boost::bind( &au::SessionTokenTestConnection::HandleContentRead, shared_from_this(), asio::placeholders::bytes_transferred, asio::placeholders::error ) ); } else { // Execute the handler. (handler_it->second)(std::move(request_)); } }