void
RPG_Graphics_Cursor_Manager::setCursor(const RPG_Graphics_Cursor& type_in,
                                       SDL_Rect& dirtyRegion_out,
                                       const bool& lockedAccess_in)
{
  RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::setCursor"));

  // step0: init return value(s)
  ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out));

  // step1: load graphic (check cache first)
  RPG_Graphics_Cursor_CacheConstIterator_t iterator = myCache.find(type_in);
  if (iterator != myCache.end())
    myCurrentGraphic = (*iterator).second;
  else
  {
    // not in cache --> (try to) load graphic
    RPG_Graphics_GraphicTypeUnion type;
    type.discriminator = RPG_Graphics_GraphicTypeUnion::CURSOR;
    type.cursor = type_in;
    RPG_Graphics_t graphic;
    graphic.category = RPG_GRAPHICS_CATEGORY_INVALID;
    graphic.type.discriminator = RPG_Graphics_GraphicTypeUnion::INVALID;
    // retrieve properties from the dictionary
    graphic = RPG_GRAPHICS_DICTIONARY_SINGLETON::instance()->get(type);
    ACE_ASSERT((graphic.type.cursor == type_in) &&
               (graphic.type.discriminator == RPG_Graphics_GraphicTypeUnion::CURSOR));
    // sanity check
    if (graphic.category != CATEGORY_CURSOR)
    {
      ACE_DEBUG((LM_ERROR,
                 ACE_TEXT("invalid category (was: \"%s\"): \"%s\" not a cursor type, aborting\n"),
                 ACE_TEXT(RPG_Graphics_CategoryHelper::RPG_Graphics_CategoryToString(graphic.category).c_str()),
                 ACE_TEXT(RPG_Graphics_CursorHelper::RPG_Graphics_CursorToString(type_in).c_str())));

      return;
    } // end IF

    // assemble path
    std::string filename;
    RPG_Graphics_Common_Tools::graphicToFile(graphic, filename);
    ACE_ASSERT(!filename.empty());

    // load file
    myCurrentGraphic = NULL;
    myCurrentGraphic = RPG_Graphics_Surface::load(filename, // file
                                                  true);    // convert to display format
    if (!myCurrentGraphic)
    {
      ACE_DEBUG((LM_ERROR,
                 ACE_TEXT("failed to RPG_Graphics_Surface::load(\"%s\"), aborting\n"),
                 ACE_TEXT(filename.c_str())));

      return;
    } // end IF

    // update cache
    myCache.insert(std::make_pair(type_in, myCurrentGraphic));

    iterator = myCache.find(type_in);
    ACE_ASSERT(iterator != myCache.end());
  } // end ELSE

  // step1: restore old background
  if (myScreenLock && lockedAccess_in)
    myScreenLock->lock();
  restoreBG(dirtyRegion_out,
            NULL,
            false);
  if (myScreenLock && lockedAccess_in)
    myScreenLock->unlock();

  // step2: create background surface
  if (myBG)
  {
    SDL_FreeSurface(myBG);
    myBG = NULL;
  } // end IF
  myBG = RPG_Graphics_Surface::create((*iterator).second->w,
                                      (*iterator).second->h);
  if (!myBG)
  {
    ACE_DEBUG((LM_ERROR,
                ACE_TEXT("failed to RPG_Graphics_Surface::create(%u,%u), aborting\n"),
                (*iterator).second->w, (*iterator).second->h));

    return;
  } // end IF
  myBGPosition = std::make_pair(std::numeric_limits<unsigned int>::max(),
                                std::numeric_limits<unsigned int>::max());

//     ACE_DEBUG((LM_DEBUG,
//                ACE_TEXT("set cursor to: \"%s\"\n"),
//                ACE_TEXT(RPG_Graphics_TypeHelper::RPG_Graphics_TypeToString(type_in).c_str())));

  myCurrentType = type_in;
}
//
// init
//
int Tena_Data_Channel_Subscriber::init (int argc, ACE_TCHAR * argv [])
{
  try
  {
    // Parse the configuration and initialize the TENA middleware.
    this->config_.parse (argc, argv);
    this->runtime_ = TENA::Middleware::init (this->config_.tenaConfiguration ());

    // Extract the current settings from the configuration.
    std::string channel = this->config_["channelName"].getValue <std::string> ().c_str ();
    TENA::uint32 verbosity = this->config_["verbosity"].getValue <TENA::uint32>();
    bool self_reflection = this->config_["enableSelfReflection"].getValue< bool >();
    bool want_pruning = this->config_["pruneExpiredStateChange"].getValue< bool >();

    TENA::Middleware::CommunicationProperties
      communication_properties = this->config_["bestEffort"].isSet() ?
      TENA::Middleware::BestEffort : TENA::Middleware::Reliable;

    // Extract the endpoint and join the specified TENA execution.
    TENA::Middleware::Endpoint endpoint = this->config_["emEndpoint"].getValue <TENA::Middleware::Endpoint> ();
    this->execution_ = this->runtime_->joinExecution (endpoint);

    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("%T (%t) - %M - joining execution %s\n"),
                endpoint.toString ().c_str ()));

    // Extract the session from the configuration. We are going to
    // use this to determine what session we should join.
    std::string session = this->config_["sessionName"].getValue <std::string> ().c_str ();
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("%T (%t) - %M - joining session %s\n"),
                session.c_str ()));

    this->session_ = this->execution_->createSession (session);

    // Create a new data channel subscription pointer. We are then
    // going to subscribe, but we do not allow self-reflection (i.e.,
    // we can't receive our own objects) since it does not make sense
    // in this case.
    this->data_subscription_.reset (new OASIS::Middleware::DataChannel::Subscription ());
    this->registration_subscription_.reset (new OASIS::Middleware::RegistrationChannel::Subscription ());

    // Create the observer and add it to the subscription(s).
    Einode_Observer * observer = new Einode_Observer (*this);
    this->observer_.reset (observer);

    this->registration_subscription_->addObserver (
      OASIS::Middleware::RegistrationChannel::AbstractObserverPtr (observer));

    OASIS::Middleware::RegistrationChannel::subscribe (*this->session_,
                                                       this->registration_subscription_,
                                                       false);

    this->data_subscription_->addObserver (
      OASIS::Middleware::DataChannel::AbstractObserverPtr (observer));

    OASIS::Middleware::DataChannel::subscribe (*this->session_,
                                               this->data_subscription_,
                                               false);

    // We can now start listening for callbacks.
    this->task_.reset (this->session_);
    this->task_.activate ();

    return 0;
  }
  catch (const TENA::Middleware::ConfigurationError & ex)
  {
    std::cerr << "Configuration Error: \n" << ex.what() << std::endl;
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%T (%t) - %M - Configuration Error: %s\n"),
                ex.what ()));
  }
  catch (const std::exception & ex)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%T (%t) - %M - Error: Exception raised: %s\n"),
                ex.what ()));
  }
  catch (...)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%T (%t) - %M - caught unknown exception\n")));
  }

  return -1;
}
void
Receiver_exec_i::ccm_remove (void)
{
    //DDS_Get
    if (!this->getter_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get getter failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get getter passed\n")));
    }
    if (!this->getter_dds_data_reader_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get DDS reader of DDS_Get failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get DDS reader of DDS_Get passed\n")));
    }
    if (!this->getter_reader_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get reader of DDS_Get failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get reader of DDS_Get passed\n")));
    }
    if (!this->getter_filter_config_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get filter config of DDS_Get failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get filter config of DDS_Get passed\n")));
    }
    //DDS_Listen
    if (!this->listen_data_control_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get data listen control of DDS_Listen failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get data listen control of DDS_Listen passed\n")));
    }
    if (!this->listen_reader_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get reader of DDS_Listen failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get reader of DDS_Listen passed\n")));
    }
    if (!this->listen_dds_data_reader_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get dds reader of DDS_Listen failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get dds reader of DDS_Listen passed\n")));
    }
    if (!this->listen_filter_config_ok_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : get filter config of DDS_Listen failed\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Get filter config of DDS_Listen passed\n")));
    }
    //Provides
    if (!this->raw_listener_created_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : listener not created\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : Listener was created\n")));
    }
    if (!this->listen_port_status_created_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : PortStatusListener of DDS_Listen not created\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : PortStatusListener of DDS_Listen was created\n")));
    }
    if (!this->get_port_status_created_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : PortStatusListener of DDS_Get not created\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : PortStatusListener of DDS_Get was created\n")));
    }
    if (!this->get_status_listener_created_)
    {
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Receiver : ConnectorStatusListener not created\n")));
    }
    else
    {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Receiver : ConnectorStatusListener was created\n")));
    }
}
示例#4
0
int KSGateway::setupAllDevices()
{
	DRTPPoolType::SmartObject obj;
	int ret;
	
	ret = device_factory_init(KSG_LOOP_DEV);
	if(ret)
	{
		return -1;
	}
	ACE_DEBUG((LM_INFO,"下载设备参数"));
	obj = KsgGetDrtpPool()->Alloc();
	obj->SetRequestHeader(_configuration._drtpGetDevFuncNo,1);
	obj->AddField(F_LCERT_CODE,_configuration._gwId); // ID
	obj->AddField(F_SCUST_LIMIT2,_configuration._dynaKey.c_str()); // dynamic key
	if(obj->Connect())
	{
		return -1;
	}
	if(obj->SendRequest(3000))
	{
		ACE_DEBUG((LM_ERROR,"下载设备参数失败"));
		return -1;
	}
	else if(obj->GetReturnCode())
	{
		ACE_DEBUG((LM_ERROR,"下载设备参数失败[%s]",obj->GetReturnMsg().c_str()));
		return -1;
	}
	if(obj->HasMoreRecord())
	{
		while(obj->HasMoreRecord())
		{
			ST_PACK * data = obj->GetNextRecord();
			// 获取设备的参数
			NormalDeviceType dt = data->semp;
			std::string devphyid = data->sname;
			std::string ipaddr = data->sname2;
			std::string devname = data->scust_limit; // 设备名称
			std::string vendor = data->sdate0;
			// 连接方式, 默认为 TCP 
			KSGDeviceURL::DevConnType conn_type = static_cast<KSGDeviceURL::DevConnType>(data->lvol5); 			
			char addr[512];
			int devport = data->lvol2;
			try
			{
				ACE_DEBUG((LM_DEBUG,"设备[%d][%s]类型[%s]物理ID[%s]机号[%d]"
					,data->lvol0,devname.c_str(),dt.c_str(),devphyid.c_str(),devport));
				// 设备厂商标识
				DeviceNodeType * device = _devManager->NewDevice(data->lvol0,data->lvol1,vendor,devphyid,dt);
				// 设备地址信息
				if(conn_type == KSGDeviceURL::dctCOM)
					ACE_OS::sprintf(addr,"dev:COM:%s//%d@%s:%d",vendor.c_str()
									,devport,ipaddr.c_str(),data->lvol4);
				else if(conn_type == KSGDeviceURL::dctTCP)
					ACE_OS::sprintf(addr,"dev:TCP:%s//%d@%s:%d",vendor.c_str()
									,devport,ipaddr.c_str(),data->lvol4);
				else if(conn_type == KSGDeviceURL::dctModem)
					ACE_OS::sprintf(addr,"dev:MDM:%s//%d@%s:%d",vendor.c_str()
					,devport,ipaddr.c_str(),data->lvol4);
				else if(conn_type == KSGDeviceURL::dctSubLevel)
					ACE_OS::sprintf(addr,"dev:SUB:%s//%d@",vendor.c_str()
					,devport);
				else
					throw DeviceAddrUrlException();
				device->SetAddrUrl(addr);
				device->set_name(devname);
				device->set_vendor(vendor);
				// 设备机号
				device->SetTermId(data->lvol3);
				device->set_port_count(data->lvol6);
			}
			catch (DeviceIdAlreadyExists&)
			{
				ACE_DEBUG((LM_ERROR,"设备[%d][%s]的已经存在!!!",data->lvol0,devname.c_str()));
				return -1;
			}
			catch(DevTypeNotExists&)
			{
				ACE_DEBUG((LM_ERROR,"设备类型不存在!设备[%d][%s]类型[%s]"
					,data->lvol0,devname.c_str(),dt.c_str()));
				continue;
			}
			catch(DeviceAddrUrlException&)
			{
				ACE_DEBUG((LM_ERROR,"设备的地址信息错误!设备[%d]addr[%s]"
					,data->lvol0,data->vsvarstr0));
				continue;
			}
		}
		ACE_DEBUG((LM_INFO,"共下载[%d]个设备",_devManager->GetDeviceCount()));
		// 将设备按照父ID号进行排序, 
		// 并生成树结构 2006-12-30
		/*
		if(_devManager->Sort())
		{
			return -1;
		}*/
		_devManager->Sort();
	 	
		// 按照厂商配置将所有的设备类型进行初始化
		vendor_map_type::const_iterator iter;
		for(iter = _vender_config.begin();iter != _vender_config.end();++iter)
		{
			if(iter->first == KSG_LOOP_DEV)
				continue;
			// 如果不支持的设备厂商接口,只提示错误信息
			ret = device_factory_init(iter->first);
			if(ret)
			{
				ACE_DEBUG((LM_ERROR,"初始化设备厂商硬件接口错误[%s]",(iter->first).c_str()));
				//return -1;
				if(ret!=-3)
					return -1;
			}
		}
		return 0;
	}
	ACE_DEBUG((LM_ERROR,"无设备参数...[%s]",obj->GetReturnMsg().c_str()));
	return 0;
}
示例#5
0
文件: server.cpp 项目: CCJY/ATCD
int
ACE_TMAIN(int, ACE_TCHAR **argv)
{
  int result = 0;

  ACE_TCHAR signum[64];
  ACE_OS::sprintf(signum, ACE_TEXT("%d"), SIGUSR1);

  ACE_ARGV args;
  args.add(argv[0]);
  args.add(ACE_TEXT("-s"));
  args.add(signum);

  ACE_Service_Config &serviceConfig = *ACE_Service_Config::singleton ();

  result = serviceConfig.open (args.argc(),
                               args.argv(),
                               ACE_DEFAULT_LOGGER_KEY,
                               true, // ignore_static_svcs = 1,
                               true, // ignore_default_svc_conf_file = 0,
                               false  // ignore_debug_flag = 0
                               );

  if(0 != result)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("serviceConfig.open failed\n")));
      return result;
    }
  ACE_DEBUG ((LM_INFO, ACE_TEXT ("serviceConfig.open done\n")));

  for(int i = 0; i < 5; ++i)
    {
      ACE_DEBUG ((LM_INFO, ACE_TEXT ("loadOrb ...\n")));
      result = loadOrb(serviceConfig);
      if(0 != result)
        {
          ACE_ERROR ((LM_ERROR, ACE_TEXT ("loadOrb failed\n")));
          return result;
        }
      ACE_DEBUG ((LM_INFO, ACE_TEXT ("loadOrb done\n")));

      ACE_DEBUG ((LM_INFO, ACE_TEXT ("loadNotify ...\n")));
      result = loadNotify(serviceConfig);
      if(0 != result)
        {
          ACE_ERROR ((LM_ERROR, ACE_TEXT ("loadNotify failed\n")));
          return result;
        }
      ACE_DEBUG ((LM_INFO, ACE_TEXT ("loadNotify done\n")));

      ACE_DEBUG ((LM_INFO, ACE_TEXT ("unloadNotify ...\n")));
      result = unloadNotify(serviceConfig);
      if(0 != result)
        {
          ACE_ERROR ((LM_ERROR, ACE_TEXT ("unloadNotify failed\n")));
          return result;
        }
      ACE_DEBUG ((LM_INFO, ACE_TEXT ("unloadNotify done\n")));

      ACE_DEBUG ((LM_INFO, ACE_TEXT ("unloadOrb ...\n")));
      result = unloadOrb(serviceConfig);
      if(0 != result)
        {
          ACE_ERROR ((LM_ERROR, ACE_TEXT ("unloadOrb failed\n")));
          return result;
        }
      ACE_DEBUG ((LM_INFO, ACE_TEXT ("unloadOrb done\n")));
    }

  ACE_DEBUG ((LM_INFO, ACE_TEXT ("serviceConfig.fini_svcs ...\n")));
  result = serviceConfig.fini_svcs();
  if(0 != result)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("serviceConfig.fini_svcs failed\n")));
      return result;
    }
  ACE_DEBUG ((LM_INFO, ACE_TEXT ("serviceConfig.fini_svcs done\n")));

  ACE_DEBUG ((LM_INFO, ACE_TEXT ("serviceConfig.close ...\n")));
  result = serviceConfig.close();
  if(0 != result)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("serviceConfig.close failed\n")));
      return result;
    }
  ACE_DEBUG ((LM_INFO, ACE_TEXT ("serviceConfig.close done\n")));

  return 0;
}
示例#6
0
void
SubDriver::run()
{
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT("(%P|%t) SubDriver::run, ")
              ACE_TEXT(" Wait for %s. \n"),
              pub_id_fname_.c_str ()));

  PublicationIds ids;

  // Wait for the publication id file created by the publisher.
  while (1)
  {
    FILE* fp
      = ACE_OS::fopen (pub_id_fname_.c_str (), ACE_TEXT("r"));
    if (fp == 0)
    {
      ACE_OS::sleep (1);
    }
    else
    {
      // This could be made cleaner  by losing the old C-style I/O.
      ::OpenDDS::DCPS::PublicationId pub_id = OpenDDS::DCPS::GUID_UNKNOWN;
      char charBuffer[64];
      while (fscanf (fp, "%s\n", &charBuffer[0]) != EOF)
      {
        std::stringstream buffer( charBuffer);
        buffer >> pub_id;
        ids.push_back (pub_id);

        std::stringstream idBuffer;
        idBuffer << pub_id;
        ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT("(%P|%t) SubDriver::run, ")
              ACE_TEXT(" Got from %s: pub_id=%C. \n"),
              pub_id_fname_.c_str (),
              buffer.str().c_str()));
      }
      ACE_OS::fclose (fp);
      break;
    }
  }

  CORBA::Object_var object =
    orb_->string_to_object (pub_driver_ior_.c_str ());

  pub_driver_ = ::Test::TestPubDriver::_narrow (object.in ());

  TEST_CHECK (!CORBA::is_nil (pub_driver_.in ()));

  size_t num_publications = ids.size ();

  // Set up the publications.
  OpenDDS::DCPS::AssociationData* publications
    = new OpenDDS::DCPS::AssociationData[num_publications];


  for (size_t i = 0; i < num_publications; i ++)
  {
    publications[i].remote_id_                = ids[i];
    publications[i].remote_data_.transport_id = ALL_TRAFFIC; // TBD later - wrong
    publications[i].remote_data_.publication_transport_priority = 0;

    OpenDDS::DCPS::NetworkAddress network_order_address(this->pub_addr_str_);

    ACE_OutputCDR cdr;
    cdr << network_order_address;
    size_t len = cdr.total_length ();

    publications[i].remote_data_.data
      = OpenDDS::DCPS::TransportInterfaceBLOB
      (len,
      len,
      (CORBA::Octet*)(cdr.buffer ()));
  }

  this->subscriber_.init(ALL_TRAFFIC,
                         this->sub_id_,
                         num_publications,
                         publications,
                         receive_delay_msec_);

  delete [] publications;

  while (this->subscriber_.received_test_message() != num_writes_)
    {
      ACE_OS::sleep(1);
    }

  pub_driver_->shutdown ();

  // Sleep before release transport so the connection will not go away.
  // This would avoid the problem of publisher sendv failure due to lost
  // connection during the shutdown period.
  ACE_OS::sleep (5);

  OpenDDS::DCPS::WriterIdSeq writers;
  writers.length(num_publications);
  for (size_t i = 0; i < num_publications; ++i) {
    writers[i] = ids[i];
  }

  this->subscriber_.remove_associations(num_publications, writers.get_buffer(), this->sub_id_);

  // Tear-down the entire Transport Framework.
  TheTransportFactory->release();
  TheServiceParticipant->shutdown();
}
示例#7
0
int KSGateway::run()
{
	long sleep_time = 0;
	int ret = loadLocalConfig();
	if(ret)
		return ret;
	ret = setupLogSystem();
	if(ret)
		return ret;
	ACE_DEBUG((LM_INFO,"开始启动前置机..."));
	ACE_DEBUG((LM_INFO,"应用服务器[%s:%d]func[%d]",_configuration._drtpSvrIP.c_str()
		,_configuration._drtpSvrPort,_configuration._drtpMainFunc));

	ret = setupDrtpPool();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"初始化DRTP连接失败,返回码[%d]",ret));
		return ret;
	}
	
	ret = enroll();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"前置机签到失败,错误码[%d]",ret));
		return ret;
	}
	ret = downloadRuntimeParams(&_configuration);
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"下载运行参数失败,错误码[%d]",ret));
		return ret;
	}
	
	ret = load_vendor_config();
	if(ret)
	{
		return ret;
	}
	// 加载 loop 设备
	/*
	ret = loadLoopDevice();
	if(ret)
	{
		return ret;
	}
	*/

	ret = setupAllDevices();
	if(ret)
	{
		return ret;
	}
	//ACE_DEBUG((LM_INFO,"前置机未加载设备!"));
	loadTaskExecutor();

	_status = stRunning;

	ret = setup_all_proactor_acceptor();

	// 2007-04-19
	// 为防止调度线程在接收任务线程之后启动,当任务队列中只有一条任务的
	// 情况下,可能造成的饥饿死锁,应先启动调度线程。但是这种处理办法并
	// 不是最好的,应该增加信号量来控制任务采集线程晚于调度线程启动.
	ret = start_scheduler_algorithm();
	if(ret)
		return ret;

	ret = startTimeScheduler();
	if(ret)
		return ret;
	
	
	ACE_DEBUG((LM_INFO,"启动前置机成功..."));
	// 进入主循环
	
	int i = 0;
	while(_status == stRunning)
	{
		KSGThreadUtil::Sleep(5000);
		sleep_time += 5000;
		if(sleep_time > 1000 * 60 * 15)
		{
			report_status();
			KSGConfig config;
			config = _configuration;
			if(downloadRuntimeParams(&config) == 0)
			{
				ACE_DEBUG((LM_DEBUG,"更新前置机参数,gwid[%d]",config._gwId));
				_configuration = config;
			}
			sleep_time = 0;
		}
		KSGThreadUtil::yield();
	}
	ACE_DEBUG((LM_INFO,"正在停止前置机..."));
	stop_all_proactor_acceptor();
	SchedulerGroup::Instance().TerminateAll();
	// 使用循环等待方式,控制超时
	/*
	while(_status == stRunning)
	{
		ACE_Time_Value tv(5);
		tv += ACE_OS::gettimeofday();
		ACE_DEBUG((LM_DEBUG,"等待超时,准备重试"));
	}
	*/
	_status = stStop;
	//_devgrpSchd.TerminateAll();
	stop_scheduler_algorithm();
	ACE_DEBUG((LM_INFO,"主流程运行结束"));
	exit();
	return 0;
}
示例#8
0
static void
test_timed_wait (int nesting_level,
                 ACE_TEST_MUTEX *rm)
{
  // Make sure that we're inside of a recursive level.
  if (nesting_level == 0)
    test_timed_wait (nesting_level + 1,
                     rm);
  else
    {
      u_int seed = (u_int) ACE_OS::time (0);

      for (size_t i = 0; i < ACE_MAX_ITERATIONS / 2; i++)
        {
          int result = 0;

          // First attempt to acquire the mutex with a timeout to verify
          // that mutex timeouts are working.

          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) = trying timed acquire on ")
                      ACE_TEXT ("iteration %d\n"),
                      i));

          ACE_Time_Value delta (1, 0);  // One second timeout
          ACE_Time_Value timeout = ACE_OS::gettimeofday ();
          timeout += delta;  // Must pass absolute time to acquire().

          if (rm->acquire (timeout) != 0)
            {
              if (errno == ETIME)
                ACE_DEBUG ((LM_DEBUG,
                            ACE_TEXT ("(%P|%t) = mutex acquisition ")
                            ACE_TEXT ("timed out\n")));
              else if (errno == ENOTSUP)
                {
#if !defined (ACE_HAS_MUTEX_TIMEOUTS)
                  if (!reported_notsup)
                    {
                      ACE_DEBUG ((LM_INFO,
                                  ACE_TEXT ("(%P|%t) %p, but ACE_HAS_MUTEX_TIMEOUTS is not defined - Ok\n"),
                                  ACE_TEXT ("mutex timed acquire")));
                      reported_notsup = 1;
                    }
#else
                  ACE_DEBUG ((LM_ERROR,
                              ACE_TEXT ("(%P|%t) %p - maybe ACE_HAS_MUTEX_TIMEOUTS should not be defined?\n"),
                              ACE_TEXT ("mutex timed acquire")));
#endif  /* ACE_HAS_MUTEX_TIMEOUTS */
                }
              else
                {
                  ACE_ERROR ((LM_ERROR,
                              ACE_TEXT ("(%P|%t) %p\n%a"),
                              ACE_TEXT ("mutex timeout failed\n")));
                  return;
                }
            }
          else
            {
              result = rm->release ();
              ACE_TEST_ASSERT (result == 0);
            }

          // Now try the standard mutex.

          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) = trying to acquire on iteration %d\n"),
                      i));
          result = rm->acquire ();
          ACE_TEST_ASSERT (result == 0);
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) = acquired on iteration %d\n"),
                      i));

          // Sleep for a random amount of time between 0 and 2 seconds.
          // Note that it's ok to use rand() here because we are running
          // within the critical section defined by the Thread_Mutex.
          ACE_OS::sleep (ACE_OS::rand_r (&seed) % 2);

          result = rm->release ();
          ACE_TEST_ASSERT (result == 0);
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) = released on iteration %d\n"),
                      i));

          // FUZZ: disable check_for_ACE_Guard
          // Basic ACE_Guard usage - automatically acquire the mutex on
          // guard construction and automatically release it on
          // destruction.
          {
            // Construct an ACE_Guard to implicitly acquire the mutex.
            ACE_Guard<ACE_TEST_MUTEX> guard (*rm);
            ACE_TEST_ASSERT (guard.locked () != 0);

            // Perform some operation which might exit the current scope
            // prematurely, e.g. by returning or throwing an exception.
            // ...

            // ACE_Guard object is destroyed when exiting scope and guard
            // destructor automatically releases mutex.
          }

          // Use an ACE_Guard to automatically acquire a mutex, but release
          // the mutex early.
          {
            // Construct an ACE_Guard to implicitly acquire the mutex.
            ACE_Guard<ACE_TEST_MUTEX> guard (*rm);
            ACE_TEST_ASSERT (guard.locked () != 0);

            // Perform some operation which might exit the current scope
            // prematurely, e.g. by returning or throwing an exception.
            // ...

            // Release the mutex since we no longer need it.
            guard.release ();
            ACE_TEST_ASSERT (guard.locked () == 0);

            // Do something else which does not require the mutex to be locked.
            // ...

            // ACE_Guard object's destructor will not release the mutex.
          }

          // Use an ACE_Guard to automatically acquire a mutex, but
          // relinquish ownership of the lock so that the mutex is not
          // automatically released on guard destruction. This is useful
          // when an operation might not release the mutex in some
          // conditions, in which case responsibility for releasing it is
          // passed to someone else.
          {
            // Construct an ACE_Guard to implicitly acquire the mutex.
            ACE_Guard<ACE_TEST_MUTEX> guard (*rm);
            ACE_TEST_ASSERT (guard.locked () != 0);

            // Perform some operation which might exit the current scope
            // prematurely, e.g. by returning or throwing an exception.
            // ...

            // Relinquish ownership of the mutex lock. Someone else must
            // now release it.
            guard.disown ();
            ACE_TEST_ASSERT (guard.locked () == 0);

            // ACE_Guard object's destructor will not release the mutex.
        }
          // We are now responsible for releasing the mutex.
          result = rm->release ();
          ACE_TEST_ASSERT (result == 0);

          // Construct an ACE_Guard without automatically acquiring the lock.
          {
            // Construct an ACE_Guard object without automatically
            // acquiring the mutex or taking ownership of an existing
            // lock. The third parameter tells the guard that the mutex
            // has not been locked.
            ACE_Guard<ACE_TEST_MUTEX> guard (*rm, 0, 0);
            ACE_TEST_ASSERT (guard.locked () == 0);

            // Conditionally acquire the mutex.
            if (i % 2 == 0)
              {
                guard.acquire ();
                ACE_TEST_ASSERT (guard.locked () != 0);
              }

            // Perform some operation that might exit the current scope
            // prematurely, e.g. by returning or throwing an exception.
            // ...

            // ACE_Guard object is destroyed when exiting scope and guard
            // destructor automatically releases if it was acquired above.
          }

          // Use an ACE_Guard to take ownership of a previously acquired
          // mutex.
          timeout = ACE_OS::gettimeofday ();
          timeout += delta;  // Must pass absolute time to acquire().
          if (rm->acquire (timeout) == 0)
            {
              // Construct an ACE_Guard object without automatically
              // acquiring the mutex, but instead take ownership of the
              // existing lock.  The third parameter tells the guard that
              // the mutex has already been locked.
              ACE_Guard<ACE_TEST_MUTEX> guard (*rm, 0, 1);
              ACE_TEST_ASSERT (guard.locked () != 0);

              // Perform some operation which might exit the current scope
              // prematurely, e.g. by returning or throwing an exception.
              // ...

              // ACE_Guard object is destroyed when exiting scope and guard
              // destructor automatically releases mutex.
            }
          // FUZZ: enable check_for_ACE_Guard
        }

      return;
    }
}
示例#9
0
static void
test_recursion_depth (int nesting_level,
                      ACE_TEST_MUTEX *rm)
{
  if (nesting_level < n_iterations)
    {
#if !defined (ACE_HAS_WTHREADS)
      // This will work for Windows, too, if ACE_TEST_MUTEX is
      // ACE_Recursive_Thread_Mutex instead of ACE_Process_Mutex.
      if (nesting_level_supported
          && nesting_level != 0
          && nesting_level != rm->get_nesting_level ())
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) Pre-mutex acquire nesting ")
                      ACE_TEXT ("levels do not match.\n")));
        }
#endif  /* !ACE_HAS_WTHREADS */
      int result = rm->acquire ();
      ACE_TEST_ASSERT (result == 0);
#if !defined (ACE_HAS_WTHREADS)
      if (nesting_level_supported
          && (nesting_level + 1) != rm->get_nesting_level ())
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) Post-mutex acquire nesting ")
                      ACE_TEXT ("levels do not match.\n")));
        }

      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("(%P|%t) = acquired, nesting = %d, thread id = %u\n"),
                  rm->get_nesting_level (),
                  rm->get_thread_id ()));
#endif /* !ACE_HAS_WTHREADS */

      test_recursion_depth (nesting_level + 1,
                            rm);

#if !defined (ACE_HAS_WTHREADS)
      if (nesting_level_supported
          && (nesting_level + 1) != rm->get_nesting_level ())
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) Post recursion nesting ")
                      ACE_TEXT ("levels do not match.\n")));
        }
#endif  /* !ACE_HAS_WTHREADS */
      result = rm->release ();
      ACE_TEST_ASSERT (result == 0);
#if !defined (ACE_HAS_WTHREADS)
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("(%P|%t) = released, nesting = %d, thread id = %u\n"),
                  rm->get_nesting_level (),
                  rm->get_thread_id ()));

      if (nesting_level_supported
          && nesting_level != 0
          && nesting_level != rm->get_nesting_level ())
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) Post-mutex release nesting ")
                      ACE_TEXT ("levels do not match.\n")));
        }
#endif /* !ACE_HAS_WTHREADS */
    }
}
示例#10
0
void DCPS_IR_Domain::publish_publication_bit(DCPS_IR_Publication* publication)
{
#if !defined (DDS_HAS_MINIMUM_BIT)

  if (useBIT_) {

    DCPS_IR_Topic_Description* desc =
      publication->get_topic_description();

    const char* dataTypeName = desc->get_dataTypeName();

    bool isNotBIT =
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_TOPIC_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_SUBSCRIPTION_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_PUBLICATION_TOPIC_TYPE);

    if (isNotBIT) {
      try {
        const DDS::DataWriterQos* writerQos = publication->get_datawriter_qos();
        const DDS::PublisherQos* publisherQos = publication->get_publisher_qos();

        DCPS_IR_Topic* topic = publication->get_topic();
        const DDS::TopicQos* topicQos = topic->get_topic_qos();

        DDS::PublicationBuiltinTopicData data;
        get_BuiltinTopicKey(data.key, publication->get_id());
        get_BuiltinTopicKey(data.participant_key,
                            publication->get_participant_id());
        data.topic_name = desc->get_name();
        data.type_name = desc->get_dataTypeName();
        data.durability = writerQos->durability;
        data.durability_service = writerQos->durability_service;
        data.deadline = writerQos->deadline;
        data.latency_budget = writerQos->latency_budget;
        data.liveliness = writerQos->liveliness;
        data.reliability = writerQos->reliability;
        data.lifespan = writerQos->lifespan;
        data.user_data = writerQos->user_data;
        data.ownership = writerQos->ownership;
        data.ownership_strength = writerQos->ownership_strength;
        data.destination_order = writerQos->destination_order;
        data.presentation = publisherQos->presentation;
        data.partition = publisherQos->partition;
        data.topic_data = topicQos->topic_data;
        data.group_data = publisherQos->group_data;

        DDS::InstanceHandle_t handle
        = bitPublicationDataWriter_->register_instance(data);

        publication->set_handle(handle);

        if (OpenDDS::DCPS::DCPS_debug_level > 0) {
          ACE_DEBUG((LM_DEBUG,
                     "(%P|%t) DCPS_IR_Domain::publish_publication_bit: [ %d, 0x%x, 0x%x], handle %d.\n",
                     data.key.value[0], data.key.value[1], data.key.value[2], handle));
        }

        DDS::ReturnCode_t status = bitPublicationDataWriter_->write(data, handle);
        if (status != DDS::RETCODE_OK) {
          ACE_ERROR((LM_ERROR,
                       "(%P|%t) DCPS_IR_Domain::publish_publication_bit: write() status of %d\n",
                       status));
        }

      } catch (const CORBA::Exception& ex) {
        ex._tao_print_exception(
          "(%P|%t) ERROR: Exception caught in DCPS_IR_Domain::publish_publication_bit:");
      }

    } else {
      publication->set_bit_status(1);
    }
  }

#else
  ACE_UNUSED_ARG(publication);
#endif // !defined (DDS_HAS_MINIMUM_BIT)

}
示例#11
0
OpenDDS::DCPS::TopicStatus DCPS_IR_Domain::add_topic_i(OpenDDS::DCPS::RepoId& topicId,
                                                       const char * topicName,
                                                       const char * dataTypeName,
                                                       const DDS::TopicQos & qos,
                                                       DCPS_IR_Participant* participantPtr)
{
  DCPS_IR_Topic_Description* description;
  int descriptionLookup = find_topic_description(topicName, dataTypeName, description);

  if (1 == descriptionLookup) {
    topicId = OpenDDS::DCPS::GUID_UNKNOWN;
    return OpenDDS::DCPS::CONFLICTING_TYPENAME;

  } else if (-1 == descriptionLookup) {
    ACE_NEW_RETURN(description,
                   DCPS_IR_Topic_Description(
                     this,
                     topicName,
                     dataTypeName),
                   OpenDDS::DCPS::NOT_FOUND);

    int descriptionAddition = add_topic_description(description);

    if (0 != descriptionAddition) {
      // unable to add the topic
      delete description;
      description = 0;
      topicId = OpenDDS::DCPS::GUID_UNKNOWN;

      if (2 == descriptionAddition) {
        return OpenDDS::DCPS::CONFLICTING_TYPENAME;

      } else {
        return OpenDDS::DCPS::NOT_FOUND;
      }
    }
  }

  DCPS_IR_Topic* topic;
  ACE_NEW_RETURN(topic,
                 DCPS_IR_Topic(
                   topicId,
                   qos,
                   this,
                   participantPtr,
                   description),
                 OpenDDS::DCPS::NOT_FOUND);

  OpenDDS::DCPS::TopicStatus topicStatus = OpenDDS::DCPS::NOT_FOUND;

  switch (description->add_topic(topic)) {
  case 0: {
    switch (participantPtr->add_topic_reference(topic)) {
    case 0: {
      if (OpenDDS::DCPS::DCPS_debug_level > 0) {
        OpenDDS::DCPS::RepoIdConverter converter(topicId);
        ACE_DEBUG((LM_DEBUG,
                   ACE_TEXT("(%P|%t) DCPS_IR_Domain::add_topic_i: ")
                   ACE_TEXT("Domain %d successfully added topic %C ")
                   ACE_TEXT("at 0x%x.\n"),
                   this->id_,
                   std::string(converter).c_str(),
                   topic));
      }

      topicStatus = OpenDDS::DCPS::CREATED;

      // Keep a reference to easily locate the topic by id.
      this->idToTopicMap_[ topicId] = topic;

      // Publish the BIT information
      publish_topic_bit(topic);
    }
    break;

    case 1:

      if (OpenDDS::DCPS::DCPS_debug_level > 0) {
        OpenDDS::DCPS::RepoIdConverter converter(topicId);
        ACE_DEBUG((LM_NOTICE,
                   ACE_TEXT("(%P|%t) NOTICE: DCPS_IR_Domain::add_topic_i: ")
                   ACE_TEXT("Domain %d declined to add duplicate topic %C at 0x%x.\n"),
                   this->id_,
                   std::string(converter).c_str(),
                   topic));
      }

      topicStatus = OpenDDS::DCPS::NOT_FOUND;
      topicId = OpenDDS::DCPS::GUID_UNKNOWN;
      description->remove_topic(topic);
      delete topic;
      break;

    case -1: {
      OpenDDS::DCPS::RepoIdConverter converter(topicId);
      ACE_ERROR((LM_ERROR,
                 ACE_TEXT("(%P|%t) ERROR: DCPS_IR_Domain::add_topic_i: ")
                 ACE_TEXT("Domain %d failed to add topic %C at 0x%x.\n"),
                 this->id_,
                 std::string(converter).c_str(),
                 topic));
      topicStatus = OpenDDS::DCPS::NOT_FOUND;
      topicId = OpenDDS::DCPS::GUID_UNKNOWN;
      description->remove_topic(topic);
      delete topic;
    }
    break;
    }
  }
  break;

  case 1:

    if (OpenDDS::DCPS::DCPS_debug_level > 0) {
      OpenDDS::DCPS::RepoIdConverter converter(topicId);
      ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) WARNING: DCPS_IR_Domain::add_topic ")
                 ACE_TEXT("Unable to add topic 0x%x id %C to Topic Description\n"),
                 topic,
                 std::string(converter).c_str()));
    }

    topicStatus = OpenDDS::DCPS::NOT_FOUND;
    topicId = OpenDDS::DCPS::GUID_UNKNOWN;
    delete topic;
    break;

  case -1: {
    OpenDDS::DCPS::RepoIdConverter converter(topicId);
    ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPS_IR_Domain::add_topic ")
               ACE_TEXT("Unable to add topic 0x%x id %C to Topic Description\n"),
               topic,
               std::string(converter).c_str()));
    topicStatus = OpenDDS::DCPS::NOT_FOUND;
    topicId = OpenDDS::DCPS::GUID_UNKNOWN;
    delete topic;
  }
  break;
  }

  return topicStatus;
}
示例#12
0
void DCPS_IR_Domain::publish_topic_bit(DCPS_IR_Topic* topic)
{
#if !defined (DDS_HAS_MINIMUM_BIT)

  if (useBIT_) {
    DCPS_IR_Topic_Description* desc =
      topic->get_topic_description();
    const char* dataTypeName = desc->get_dataTypeName();

    bool isNotBIT =
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_TOPIC_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_SUBSCRIPTION_TOPIC_TYPE) &&
      ACE_OS::strcmp(dataTypeName, OpenDDS::DCPS::BUILT_IN_PUBLICATION_TOPIC_TYPE);

    if (isNotBIT) {
      try {
        const DDS::TopicQos* topicQos = topic->get_topic_qos();

        DDS::TopicBuiltinTopicData data;
        get_BuiltinTopicKey(data.key, topic->get_id());
        data.name = desc->get_name();
        data.type_name = desc->get_dataTypeName();
        data.durability = topicQos->durability;
        data.durability_service = topicQos->durability_service;
        data.deadline = topicQos->deadline;
        data.latency_budget = topicQos->latency_budget;
        data.liveliness = topicQos->liveliness;
        data.reliability = topicQos->reliability;
        data.transport_priority = topicQos->transport_priority;
        data.lifespan = topicQos->lifespan;
        data.destination_order = topicQos->destination_order;
        data.history = topicQos->history;
        data.resource_limits = topicQos->resource_limits;
        data.ownership = topicQos->ownership;
        data.topic_data = topicQos->topic_data;

        DDS::InstanceHandle_t handle =
          bitTopicDataWriter_->register_instance(data);

        topic->set_handle(handle);

        if (OpenDDS::DCPS::DCPS_debug_level > 0) {
          ACE_DEBUG((LM_DEBUG,
                     "(%P|%t) DCPS_IR_Domain::publish_topic_bit: [ %d, 0x%x, 0x%x], handle %d.\n",
                     data.key.value[0], data.key.value[1], data.key.value[2], handle));
        }

        bitTopicDataWriter_->write(data, handle);

      } catch (const CORBA::Exception& ex) {
        ex._tao_print_exception(
          "(%P|%t) ERROR: Exception caught in DCPS_IR_Domain::publish_topic_bit:");
      }

    } else {
      topic->set_bit_status(1);
    }
  }

#else
  ACE_UNUSED_ARG(topic);
#endif // !defined (DDS_HAS_MINIMUM_BIT)
}
void
RPG_Graphics_Cursor_Manager::storeHighlightBG(const RPG_Map_PositionList_t& mapPositions_in,
                                              const RPG_Graphics_Offsets_t& graphicsPositions_in,
                                              SDL_Rect& dirtyRegion_out,
                                              const bool& lockedAccess_in)
{
  RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::storeHighlightBG"));

  // sanity check
  ACE_ASSERT(myHighlightWindow);
  ACE_ASSERT(!mapPositions_in.empty());
  ACE_ASSERT(mapPositions_in.size() == graphicsPositions_in.size());

  // init return value(s)
  ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out));

  // grow/shrink cache as necessary
  int delta = myHighlightBGCache.size() - mapPositions_in.size();
  if (delta > 0)
  {
    for (int i = delta;
         i > 0;
         i--)
    {
      SDL_FreeSurface(myHighlightBGCache.back().second);
      myHighlightBGCache.pop_back();
    } // end FOR
  } // end IF
  else if (delta < 0)
  {
    SDL_Surface* new_entry = NULL;
    for (int i = -delta;
         i > 0;
         i--)
    {
      new_entry = RPG_Graphics_Surface::create(RPG_GRAPHICS_TILE_FLOOR_WIDTH,
                                               RPG_GRAPHICS_TILE_FLOOR_HEIGHT);
      if (!new_entry)
      {
        ACE_DEBUG((LM_ERROR,
                   ACE_TEXT("failed to RPG_Graphics_Surface::create(%u,%u), aborting\n"),
                   RPG_GRAPHICS_TILE_FLOOR_WIDTH,
                   RPG_GRAPHICS_TILE_FLOOR_HEIGHT));

        return;
      } // end IF
      myHighlightBGCache.push_back(std::make_pair(std::make_pair(std::numeric_limits<unsigned int>::max(),
                                                                 std::numeric_limits<unsigned int>::max()),
                                                  new_entry));
    } // end IF
  } // end ELSEIF
  ACE_ASSERT(myHighlightBGCache.size() == mapPositions_in.size());

  // step1: restore (part of) the cursor bg so it is not included. This is safe,
  // as the highlight is only redrawn when the cursor moves --> the cursor will
  // (later) be redrawn anyway...
  // --> clip to the highlight area !
  RPG_Graphics_OffsetsConstIterator_t graphics_position_iterator =
    graphicsPositions_in.begin();
  SDL_Rect clip_rectangle = {static_cast<Sint16>((*graphics_position_iterator).first),
														 static_cast<Sint16>((*graphics_position_iterator).second),
														 static_cast<Uint16>(myHighlightTile->w),
														 static_cast<Uint16>(myHighlightTile->h)};
	SDL_Rect temp_rectangle = {0, 0,
														 static_cast<Uint16>(myHighlightTile->w),
														 static_cast<Uint16>(myHighlightTile->h)};
	for (++graphics_position_iterator;
			 graphics_position_iterator != graphicsPositions_in.end();
			 graphics_position_iterator++)
	{
		temp_rectangle.x = static_cast<Sint16>((*graphics_position_iterator).first);
		temp_rectangle.y = static_cast<Sint16>((*graphics_position_iterator).second);
		clip_rectangle = RPG_Graphics_SDL_Tools::boundingBox(clip_rectangle,
																												 temp_rectangle);
	} // end FOR
  if (lockedAccess_in && myScreenLock)
    myScreenLock->lock();
  restoreBG(dirtyRegion_out,
						&clip_rectangle,
            false);
  if (lockedAccess_in && myScreenLock)
    myScreenLock->unlock();

  RPG_Graphics_TileCacheIterator_t cache_iterator = myHighlightBGCache.begin();
	graphics_position_iterator = graphicsPositions_in.begin();
//  myHighlightWindow->clip();
  for (RPG_Map_PositionListConstIterator_t map_position_iterator = mapPositions_in.begin();
       map_position_iterator != mapPositions_in.end();
       map_position_iterator++, graphics_position_iterator++, cache_iterator++)
  {
    RPG_Graphics_Surface::clear((*cache_iterator).second);
    RPG_Graphics_Surface::get(*graphics_position_iterator,
                              true, // use (fast) blitting method
                              *myHighlightWindow->getScreen(),
                              *(*cache_iterator).second);
    (*cache_iterator).first = *map_position_iterator;
  } // end FOR
//  myHighlightWindow->unclip();
}
void
RPG_Graphics_Cursor_Manager::updateBG(SDL_Rect& dirtyRegion_out,
                                      const SDL_Rect* clipRect_in,
                                      const bool& lockedAccess_in,
                                      const bool& debug_in)
{
  RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::updateBG"));

  // sanity check(s)
  ACE_ASSERT(myBG);
  ACE_ASSERT(myHighlightWindow);
  SDL_Surface* target_surface = myHighlightWindow->getScreen();
  ACE_ASSERT(target_surface);

  // init return value(s)
  ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out));

  // *NOTE*: this function handles two distinct use-cases:
  // 1. the map window has changed (clipRect_in == NULL) --> update that
  //    bit (if any) of the cached bg
  // 2. a part of the screen has changed (clipRect_in != NULL)
  // --> update that bit (if any) of the cached bg

  // step1: set clip area
  SDL_Rect clip_area = {0, 0, 0, 0};
  if (clipRect_in == NULL)
    myHighlightWindow->getArea(clip_area, false);
  else
    clip_area = *clipRect_in;

  // step2: intersect with cached bg
  SDL_Rect cached_area;
  cached_area.x = static_cast<int16_t>(myBGPosition.first);
  cached_area.y = static_cast<int16_t>(myBGPosition.second);
  cached_area.w = myBG->w;
  cached_area.h = myBG->h;
  SDL_Rect intersection = {0, 0, 0, 0};
  intersection =
      RPG_Graphics_SDL_Tools::intersect(cached_area,
                                        clip_area);
  // sanity check(s)
  if ((intersection.w == 0) || // cached bg fully outside of "dirty" area ?
      (intersection.h == 0))
    return; // --> nothing to do...
  if ((intersection.w == cached_area.w) &&
      (intersection.h == cached_area.h))
  {
    // cached cursor bg fully inside of map
    // --> just get a fresh copy
    RPG_Graphics_Surface::get(myBGPosition,
                              true, // use (fast) blitting method
                              *target_surface,
                              *myBG);

    // debug info
    if (debug_in)
    {
      // show bg surface in left upper corner
      ACE_ASSERT(target_surface->w >= myBG->w);
      ACE_ASSERT(target_surface->h >= myBG->h);

      // compute bounding box
      SDL_Rect dirty_region;
      dirty_region.x = 0;
      dirty_region.y = 0;
      dirty_region.w = myBG->w;
      dirty_region.h = myBG->h;

//      RPG_Graphics_Surface::unclip();
      if (myScreenLock && lockedAccess_in)
        myScreenLock->lock();
      RPG_Graphics_Surface::put(std::make_pair(dirty_region.x,
                                               dirty_region.y),
                                *myBG,
                                target_surface,
                                dirty_region);
      if (myScreenLock && lockedAccess_in)
        myScreenLock->unlock();
//      RPG_Graphics_Surface::clip();
    } // end IF

    return; // --> done...
  } // end IF

  // step3: adjust intersection coordinates (relative to cached bg surface)
	intersection.x -= cached_area.x;
	intersection.y -= cached_area.y;

  // step4: get a fresh copy from that part of the map
  SDL_Surface* new_bg =
		RPG_Graphics_Surface::create(static_cast<unsigned int>(myBG->w),
                                 static_cast<unsigned int>(myBG->h));
  ACE_ASSERT(new_bg);
  RPG_Graphics_Surface::get(myBGPosition,
                            true, // use (fast) blitting method
                            *target_surface,
                            *new_bg);

  // step5: mask the "dirty" bit of the cached bg
  if (SDL_FillRect(myBG,
                   &intersection,
                   RPG_Graphics_SDL_Tools::getColor(COLOR_BLACK_A0, // transparent
                                                    *myBG)))
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("failed to SDL_FillRect(): \"%s\", aborting\n"),
               ACE_TEXT(SDL_GetError())));

    // clean up
    SDL_FreeSurface(new_bg);

    return;
  } // end IF

  // step6: blit the cached bg onto the fresh copy
  if (SDL_BlitSurface(myBG,   // source
                      NULL,   // aspect (--> everything)
                      new_bg, // target
                      NULL))  // aspect (--> everything)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("failed to SDL_BlitSurface(): %s, aborting\n"),
               ACE_TEXT(SDL_GetError())));

    // clean up
    SDL_FreeSurface(new_bg);

    return;
  } // end IF

  // clean up
  SDL_FreeSurface(myBG);

  myBG = new_bg;

  // debug info
  if (debug_in)
  {
    // show bg surface in left upper corner
    ACE_ASSERT(target_surface->w >= myBG->w);
    ACE_ASSERT(target_surface->h >= myBG->h);

    // compute bounding box
    SDL_Rect dirty_region;
    dirty_region.x = 0;
    dirty_region.y = 0;
    dirty_region.w = myBG->w;
    dirty_region.h = myBG->h;

//    RPG_Graphics_Surface::unclip();
    if (myScreenLock && lockedAccess_in)
      myScreenLock->lock();
    RPG_Graphics_Surface::put(std::make_pair(dirty_region.x,
                                             dirty_region.y),
                              *myBG,
                              target_surface,
                              dirty_region);
    if (myScreenLock && lockedAccess_in)
      myScreenLock->unlock();
//    RPG_Graphics_Surface::clip();
  } // end IF
}
示例#15
0
int ACE_TMAIN(int argc, ACE_TCHAR* argv[])
{

  int status = 0;

  try
    {
      ::DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs(argc, argv);

      // let the Service_Participant (in above line) strip out -DCPSxxx parameters
      // and then get application specific parameters.
      parse_args(argc, argv);

      ::Xyz::FooTypeSupport_var fts (new ::Xyz::FooTypeSupportImpl);

      ::DDS::DomainParticipant_var dp =
        dpf->create_participant(MY_DOMAIN,
                                PARTICIPANT_QOS_DEFAULT,
                                ::DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (dp.in ()))
      {
        ACE_ERROR ((LM_ERROR,
                   ACE_TEXT("(%P|%t) create_participant failed.\n")));
        return 1 ;
      }

      if (::DDS::RETCODE_OK != fts->register_type(dp.in (), MY_TYPE))
        {
          ACE_ERROR ((LM_ERROR,
            ACE_TEXT ("Failed to register the FooTypeSupport.")));
          return 1;
        }


      ::DDS::TopicQos topic_qos;
      dp->get_default_topic_qos(topic_qos);

      ::DDS::Topic_var topic =
        dp->create_topic (MY_TOPIC,
                          MY_TYPE,
                          TOPIC_QOS_DEFAULT,
                          ::DDS::TopicListener::_nil(),
                          ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ()))
      {
        return 1 ;
      }

      ::DDS::TopicDescription_var description =
        dp->lookup_topicdescription(MY_TOPIC);
      if (CORBA::is_nil (description.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) lookup_topicdescription failed.\n")),
                           1);
      }

      // Create the subscriber
      ::DDS::Subscriber_var sub =
        dp->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                             ::DDS::SubscriberListener::_nil(),
                             ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (sub.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) create_subscriber failed.\n")),
                           1);
      }

      // Create the Datareaders
      ::DDS::DataReaderQos dr_qos;
      sub->get_default_datareader_qos (dr_qos);

      dr_qos.liveliness.lease_duration.sec = LEASE_DURATION_SEC;
      dr_qos.liveliness.lease_duration.nanosec = 0;

      ::DDS::DataReaderListener_var drl (new DataReaderListenerImpl);
      DataReaderListenerImpl* drl_servant =
        dynamic_cast<DataReaderListenerImpl*>(drl.in());

      if (!drl_servant) {
        ACE_ERROR_RETURN((LM_ERROR,
          ACE_TEXT("%N:%l main()")
          ACE_TEXT(" ERROR: drl_servant is nil (dynamic_cast failed)!\n")), -1);
      }

      ::DDS::DataReader_var dr ;

      dr = sub->create_datareader(description.in (),
                                  dr_qos,
                                  drl.in (),
                                  ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      ACE_OS::sleep(test_duration);

      // clean up subscriber objects


      sub->delete_contained_entities() ;

      dp->delete_subscriber(sub.in ());

      dp->delete_topic(topic.in ());
      dpf->delete_participant(dp.in ());

      TheServiceParticipant->shutdown ();

      if( drl_servant->deadline_missed() < threshold_liveliness_lost) {
        ACE_ERROR((LM_ERROR,
          ACE_TEXT("(%P|%t) subscriber: ")
          ACE_TEXT("liviness deadline not violated enough for test. ")
          ACE_TEXT("Got %d, expected at least %d.\n"),
          drl_servant->deadline_missed(),
          threshold_liveliness_lost
        ));
        return 1;

      } else {
        ACE_DEBUG((LM_INFO,
          ACE_TEXT("(%P|%t) subscriber: ")
          ACE_TEXT("liviness deadline violated enough for test. ")
          ACE_TEXT("Got %d, expected at least %d.\n"),
          drl_servant->deadline_missed(),
          threshold_liveliness_lost
        ));
      }
    }
  catch (const TestException&)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT("(%P|%t) TestException caught in main.cpp. ")));
      return 1;
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught in main.cpp:");
      return 1;
    }

  return status;
}
示例#16
0
文件: MIF.cpp 项目: Kintoun/POSA
int ACE_TMAIN (int,ACE_TCHAR**)
{
  Kokyu::DSRT_ConfigInfo config_info;

  //  config_info.scheduler_type_ = Kokyu::SCHED_MIF;
  config_info.impl_type_ = Kokyu::DSRT_OS_BASED;

  ACE_Barrier bar (3);

  ACE_DEBUG ((LM_DEBUG, "before create_dispatcher\n" ));

  config_info.sched_strategy_ = Kokyu::DSRT_MIF;

  Kokyu::DSRT_Dispatcher_Factory<mif_scheduler_traits>::DSRT_Dispatcher_Auto_Ptr
    disp (Kokyu::DSRT_Dispatcher_Factory<mif_scheduler_traits>::
          create_DSRT_dispatcher (config_info));

  ACE_DEBUG ((LM_DEBUG, "after create_dispatcher\n" ));

  ACE_ASSERT (disp.get () != 0);

  mif_scheduler_traits::QoSDescriptor_t qos1, qos2, qos3;

  qos1.importance_ = 1;
  qos2.importance_ = 2;
  qos3.importance_ = 3;

  MyTask mytask1 (bar, disp.get (), qos1, 15);
  MyTask mytask2 (bar, disp.get (), qos2, 6);
  MyTask mytask3 (bar, disp.get (), qos3, 4);

  long flags = THR_BOUND | THR_SCHED_FIFO;

  if (mytask1.activate (flags) == -1)
    {
      flags = THR_BOUND;
      if (mytask1.activate (flags) == -1)
        ACE_ERROR ((LM_ERROR,
                        "EC (%P|%t) cannot activate task\n"));
    }

  if (mytask2.activate (flags) == -1)
    {
      flags = THR_BOUND;
      if (mytask2.activate (flags) == -1)
        ACE_ERROR ((LM_ERROR,
                        "EC (%P|%t) cannot activate task\n"));
    }

  if (mytask3.activate (flags) == -1)
    {
      flags = THR_BOUND;
      if (mytask3.activate (flags) == -1)
        ACE_ERROR ((LM_ERROR,
                        "EC (%P|%t) cannot activate task\n"));
    }

  disp->shutdown ();

  ACE_DEBUG ((LM_DEBUG, "main thread exiting\n"));

  return 0;
}
示例#17
0
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) {
  try
    {
      ACE_DEBUG ((LM_DEBUG, "(%P|%t) publisher main\n"));

      DDS::DomainParticipantFactory_var dpf =
        TheParticipantFactoryWithArgs(argc, argv);

      if (parse_args (argc, argv) == -1) {
        return -1;
      }

      DDS::DomainParticipantQos partQos;
      dpf->get_default_participant_qos(partQos);

      // set up user data in DP qos
      CORBA::ULong part_user_data_len
        = static_cast<CORBA::ULong>(ACE_OS::strlen (PART_USER_DATA));
      partQos.user_data.value.length (part_user_data_len);
      partQos.user_data.value.replace (part_user_data_len,
                                       part_user_data_len,
                                       reinterpret_cast<CORBA::Octet*>(PART_USER_DATA));

      DDS::DomainParticipant_var participant =
        dpf->create_participant(411,
                                partQos,
                                DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (participant.in ())) {
        cerr << "publisher: create_participant failed." << endl;
        return 1;
      }

      ::Messenger::MessageTypeSupport_var ts = new ::Messenger::MessageTypeSupportImpl();

      if (DDS::RETCODE_OK != ts->register_type(participant.in (), "Messenger")) {
        cerr << "publisher: register_type failed." << endl;
        exit(1);
      }

      CORBA::String_var type_name = ts->get_type_name ();

      DDS::TopicQos topic_qos;
      participant->get_default_topic_qos(topic_qos);

      // set up topic data in topic qos
      CORBA::ULong topic_data_len = static_cast<CORBA::ULong>(ACE_OS::strlen (TOPIC_DATA));
      topic_qos.topic_data.value.length (topic_data_len);
      topic_qos.topic_data.value.replace (topic_data_len, topic_data_len, reinterpret_cast<CORBA::Octet*>(TOPIC_DATA));

      DDS::Topic_var topic =
        participant->create_topic ("Movie Discussion List",
                                   type_name.in (),
                                   topic_qos,
                                   DDS::TopicListener::_nil(),
                                   ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ())) {
        cerr << "publisher: create_topic failed." << endl;
        exit(1);
      }

      DDS::PublisherQos pub_qos;
      participant->get_default_publisher_qos (pub_qos);

      // set up group data in group qos
      CORBA::ULong group_data_len = static_cast<CORBA::ULong> (ACE_OS::strlen (GROUP_DATA));
      pub_qos.group_data.value.length (group_data_len);
      pub_qos.group_data.value.replace (group_data_len, group_data_len, reinterpret_cast<CORBA::Octet*>(GROUP_DATA));

      DDS::Publisher_var pub =
        participant->create_publisher(pub_qos,
        DDS::PublisherListener::_nil(),
        ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (pub.in ())) {
        cerr << "publisher: create_publisher failed." << endl;
        exit(1);
      }

      // Create the datawriter
      DDS::DataWriterQos dw_qos;
      pub->get_default_datawriter_qos (dw_qos);
      dw_qos.durability.kind = DDS::TRANSIENT_LOCAL_DURABILITY_QOS;
      dw_qos.reliability.kind  = ::DDS::RELIABLE_RELIABILITY_QOS;
      dw_qos.resource_limits.max_samples_per_instance = 1000;
      dw_qos.history.kind  = ::DDS::KEEP_ALL_HISTORY_QOS;

      // set up user data in DW qos
      CORBA::ULong dw_user_data_len = static_cast<CORBA::ULong>(ACE_OS::strlen (DW_USER_DATA));
      dw_qos.user_data.value.length (dw_user_data_len);
      dw_qos.user_data.value.replace (dw_user_data_len,
                                      dw_user_data_len,
                                      reinterpret_cast<CORBA::Octet*>(DW_USER_DATA));

      DDS::DataWriter_var dw =
        pub->create_datawriter(topic.in (),
                               dw_qos,
                               DDS::DataWriterListener::_nil(),
                               ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (dw.in ())) {
        cerr << "publisher: create_datawriter failed." << endl;
        exit(1);
      }

      // wait for Monitor 1 done
      FILE* fp = ACE_OS::fopen (synch_fname, ACE_TEXT("r"));
      int i = 0;
      while (fp == 0 &&  i < 15)
      {
        ACE_DEBUG ((LM_DEBUG,
          ACE_TEXT("(%P|%t) waiting monitor1 done ...\n")));
        ACE_OS::sleep (1);
        ++ i;
        fp = ACE_OS::fopen (synch_fname, ACE_TEXT("r"));
      }

      if (fp != 0)
        ACE_OS::fclose (fp);

      // Now change the changeable qos. The second monitor should get the updated qos from BIT.

      part_user_data_len = static_cast<CORBA::ULong>(ACE_OS::strlen (UPDATED_PART_USER_DATA));
      partQos.user_data.value.length (part_user_data_len);
      partQos.user_data.value.replace (part_user_data_len,
                                       part_user_data_len,
                                       reinterpret_cast<CORBA::Octet*>(UPDATED_PART_USER_DATA));
      participant->set_qos (partQos);

      dw_user_data_len = static_cast<CORBA::ULong>(ACE_OS::strlen (UPDATED_DW_USER_DATA));
      dw_qos.user_data.value.length (dw_user_data_len);
      dw_qos.user_data.value.replace (dw_user_data_len,
                                      dw_user_data_len,
                                      reinterpret_cast<CORBA::Octet*>(UPDATED_DW_USER_DATA));
      dw->set_qos (dw_qos);

      group_data_len = static_cast<CORBA::ULong> (ACE_OS::strlen (UPDATED_GROUP_DATA));
      pub_qos.group_data.value.length (group_data_len);
      pub_qos.group_data.value.replace (group_data_len,
                                        group_data_len,
                                        reinterpret_cast<CORBA::Octet*>(UPDATED_GROUP_DATA));
      pub->set_qos (pub_qos);

      topic_data_len = static_cast<CORBA::ULong>(ACE_OS::strlen (UPDATED_TOPIC_DATA));
      topic_qos.topic_data.value.length (topic_data_len);
      topic_qos.topic_data.value.replace (topic_data_len,
                                          topic_data_len,
                                          reinterpret_cast<CORBA::Octet*>(UPDATED_TOPIC_DATA));
      topic->set_qos (topic_qos);

      Writer* writer = new Writer(dw.in());

      writer->start ();
      while ( !writer->is_finished()) {
        ACE_Time_Value small_time(0,250000);
        ACE_OS::sleep (small_time);
      }

      // Cleanup
      writer->end ();
      delete writer;
      participant->delete_contained_entities();
      dpf->delete_participant(participant.in ());
      TheServiceParticipant->shutdown ();
  }
  catch (CORBA::Exception& e)
    {
       cerr << "publisher: PUB: Exception caught in main.cpp:" << endl
         << e << endl;
      exit(1);
    }

  return 0;
}
示例#18
0
文件: consumer.cpp 项目: asdlei00/ACE
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    PortableServer::POAManager_var poa_manager;

    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    CORBA::Object_var poa_obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var root_poa = PortableServer::POA::_narrow(poa_obj.in());

    poa_manager = root_poa->the_POAManager();

    if (parse_args (argc, argv) != 0)
      return 1;

    poa_manager->activate();

    /*Get event_channel*/
    std::cout << "Get event_channel now"  << std::endl;
    CosNotifyChannelAdmin::EventChannel_var ec = get_event_channel(orb.in());

    //Instanciating the Consumer
    CosNotifyComm::StructuredPushConsumer_var spc =
      CosNotifyComm::StructuredPushConsumer::_nil();

    CosNotifyCommImpl::StructuredPushConsumer *pImpl_spc = new CosNotifyCommImpl::StructuredPushConsumer;
    spc = pImpl_spc->_this();

    //Obtain a Consumer Admin
    CosNotifyChannelAdmin::AdminID adminid = 0;
    CosNotifyChannelAdmin::ConsumerAdmin_var ca =
      ec->new_for_consumers (CosNotifyChannelAdmin::AND_OP, adminid);

    if( ca.in() == CosNotifyChannelAdmin::ConsumerAdmin::_nil() ){
      std::cerr << "ca is nil!" << std::endl;
      return 1;
    }

    //Obtain a Proxy Consumer
    CosNotifyChannelAdmin::ProxyID proxy_id;
    CosNotifyChannelAdmin::ClientType ctype = CosNotifyChannelAdmin::STRUCTURED_EVENT;

    CosNotifyChannelAdmin::ProxySupplier_var proxySupplier_obj;
    try
    {
      proxySupplier_obj = ca->obtain_notification_push_supplier(ctype, proxy_id);
    }
    catch(CosNotifyChannelAdmin::AdminLimitExceeded err)
    {
      std::cerr << "CosNotifyChannelAdmin::AdminLimitExceeded Exception!" << std::endl;
      throw;
    }

    CosNotifyChannelAdmin::StructuredProxyPushSupplier_var pps =
      CosNotifyChannelAdmin::StructuredProxyPushSupplier::_narrow(proxySupplier_obj.in());


    //Attaching a filter to pps
    CosNotifyFilter::FilterFactory_var dff =
      ec->default_filter_factory();

    ACE_ASSERT(!CORBA::is_nil(dff.in()));

    CosNotifyFilter::Filter_var filter = dff->create_filter("EXTENDED_TCL");

    CosNotification::EventTypeSeq event_types(1);
    event_types.length(2);

    event_types[0].domain_name = CORBA::string_dup("DomainA");
    event_types[0].type_name = CORBA::string_dup("TypeA");
    event_types[1].domain_name = CORBA::string_dup("DomainB");
    event_types[1].type_name = CORBA::string_dup("TypeB");

    CosNotifyFilter::ConstraintExpSeq constraints(1);
    constraints.length(1);

    constraints[0].event_types = event_types;
    constraints[0].constraint_expr = CORBA::string_dup(
      "");

    filter->add_constraints(constraints);

    pps->add_filter(filter.in());

    std::cout << "Attached a filter to ProxyPushSupplier" << std::endl;
    std::cout << "The filter's event_types[0].domain_name=" <<  event_types[0].domain_name << std::endl;
    std::cout << "The filter's event_types[0].type_name=" <<  event_types[0].type_name << std::endl;
    std::cout << "The filter's event_types[1].domain_name=" <<  event_types[1].domain_name << std::endl;
    std::cout << "The filter's event_types[1].type_name=" <<  event_types[1].type_name << std::endl;


    //Connecting a Supplier to a Proxy Consumer
    try
    {
      pps->connect_structured_push_consumer(spc.in());
    }
    catch (CosEventChannelAdmin::AlreadyConnected ac)
    {
      std::cerr << "CosEventChannelAdmin::AlreadyConnected" << std::endl;
      throw;
    }
    catch (CORBA::SystemException& se)
    {
      std::cerr << "System exception occurred during connect: " <<
        se << std::endl;
      throw;
    }


    ACE_Time_Value tv (runtime);
    orb->run (tv);
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Consumer done.\n")));

    if (pImpl_spc->received_events ())
    {
      //Consumer should not receive any events as it's filtered with event type.
      std::cerr << "Test failed - received test events." << std::endl;
      return 1;
    }
    else
    {
      std::cerr << "Test passed - did not receive test events as expected." << std::endl;
    }
  }
  catch(...)
  {
    std::cerr << "Consumer: Some exceptions was caught!" << std::endl;
    return 1;
  }


  return 0;
}
示例#19
0
void
SubDriver::parse_args(int& argc, ACE_TCHAR* argv[])
{
  // Command-line arguments:
  //
  // -p <pub_id_fname:pub_host:pub_port>
  // -s <sub_id:sub_host:sub_port>
  //
  ACE_Arg_Shifter arg_shifter(argc, argv);

  bool got_p = false;
  bool got_s = false;

  const ACE_TCHAR* current_arg = 0;

  while (arg_shifter.is_anything_left())
  {
    // The '-p' option
    if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-p")))) {
      if (got_p) {
        ACE_ERROR((LM_ERROR,
                   "(%P|%t) Only one -p allowed on command-line.\n"));
        throw TestException();
      }

      int result = parse_pub_arg(current_arg);
      arg_shifter.consume_arg();

      if (result != 0) {
        ACE_ERROR((LM_ERROR,
                   "(%P|%t) Failed to parse -p command-line arg.\n"));
        throw TestException();
      }

      got_p = true;
    }
    else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-n"))) != 0)
    {
      num_writes_ = ACE_OS::atoi (current_arg);
      arg_shifter.consume_arg ();
    }
    // A '-s' option
    else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-s")))) {
      if (got_s) {
        ACE_ERROR((LM_ERROR,
                   "(%P|%t) Only one -s allowed on command-line.\n"));
        throw TestException();
      }

      int result = parse_sub_arg(current_arg);
      arg_shifter.consume_arg();

      if (result != 0) {
        ACE_ERROR((LM_ERROR,
                   "(%P|%t) Failed to parse -s command-line arg.\n"));
        throw TestException();
      }

      got_s = true;
    }
    else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-v"))) != 0)
    {
      pub_driver_ior_ = ACE_TEXT_ALWAYS_CHAR (current_arg);
      arg_shifter.consume_arg ();
    }
    else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-l"))) != 0)
    {
      receive_delay_msec_ = ACE_OS::atoi (current_arg);
      arg_shifter.consume_arg ();
    }
    else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-f"))) != 0)
    {
      sub_ready_filename_ = current_arg;
      arg_shifter.consume_arg ();
    }
    // The '-?' option
    else if (arg_shifter.cur_arg_strncasecmp(ACE_TEXT("-?")) == 0) {
      ACE_DEBUG((LM_DEBUG,
                 "usage: %s "
                 "-p pub_id:pub_host:pub_port -s sub_id:sub_host:sub_port\n",
                 argv[0]));

      arg_shifter.consume_arg();
      throw TestException();
    }
    // Anything else we just skip
    else {
      arg_shifter.ignore_arg();
    }
  }

  // Make sure we got the required arguments:
  if (!got_p) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) -p command-line option not specified (required).\n"));
    throw TestException();
  }

  if (!got_s) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) -s command-line option not specified (required).\n"));
    throw TestException();
  }
}
示例#20
0
void
Sender_exec_i::stop (void)
{
    this->reactor ()->cancel_timer (this->ticker_);
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Sender_exec_i::stop : Timer canceled.\n")));
}
示例#21
0
int KSGateway::downloadRuntimeParams(KSGConfig *config)
{
	DRTPPoolType::SmartObject obj;
	ACE_DEBUG((LM_INFO,"正在下载运行参数"));
	obj = KsgGetDrtpPool()->Alloc();
	obj->SetRequestHeader(KSG_DRTP_DW_PARAMS,1);
	obj->AddField(F_LVOL0,config->_gwId); // 前置机ID
	obj->AddField(F_SCUST_LIMIT,config->_dynaKey.c_str()); // 动态密钥
	if(obj->Connect())
	{
		return -1;
	}
	if(obj->SendRequest(10000))
	{
		return -1;
	}
	else if(obj->GetReturnCode())
	{
		ACE_DEBUG((LM_ERROR,"下载前置机运行参数失败[%s]",obj->GetReturnMsg().c_str()));
		return -1;
	}
	if(obj->HasMoreRecord())
	{
		ST_PACK * data = obj->GetNextRecord();
		// 下载所有的运行参数
		config->_heartbeat = data->lvol0;
		config->_heartbeatIntval = data->lvol1;
		config->_heartbeatFuncNo = data->lvol2;
		//_configuration._drtpQueueNo = data->lvol3;
		config->_taskRecvFuncNo = data->lvol3;
		config->_taskResponseFuncNo = data->lvol9;
		if(config->_taskRecvFuncNo <= 0
			|| config->_taskResponseFuncNo <= 0)
			return -1;
		config->_execTimeout = data->lvol4;
		// FIXME : unicode
		config->_startDBTime = data->sname;
		config->_serialIntval = data->lvol5;
		config->_drtpGetDevFuncNo = data->lvol6;
		config->_taskQueueMaxWaiting = data->lvol7;
		config->_taskRecvIntval = data->lvol8;
		// TODO : 增加取任务的记录条数
		config->_get_task_count = 1;
		// 为明文密钥
#if 1
		char enkey[17] = "";
		unsigned char hexkey[17] = "";
		unsigned char hexenkey[17] = "";
		xutil::StringUtil::Str2Hex(data->sname2,hexkey,8);
		
		if(decrypt_work_key(hexkey,hexenkey) != 0)
		{
			ACE_DEBUG((LM_ERROR,"解压工作密钥失败"));
			return -1;
		}
		xutil::StringUtil::Hex2Str(hexenkey,8,enkey);
		config->_cardKey = enkey;
#else
		config->_cardKey = data->sname2;
#endif

		// FIXME: 设置了汇多设备使用的工作密钥
		ACE_OS::memset(config->_workKey,0,sizeof(config->_workKey));
		size_t keylen = ACE_OS::strlen(data->sphone);
		if(keylen == 0)
		{
			ACE_OS::strcpy(data->sphone,"ffffffffffffffff");
			keylen = ACE_OS::strlen(data->sphone);
		}
		xutil::StringUtil::Str2Hex(data->sphone,config->_workKey,(keylen+1)/2);
		return 0;
	}
	ACE_DEBUG((LM_ERROR,"未下载到参数[%s]",obj->GetReturnMsg().c_str()));
	return -1;
}
示例#22
0
int
Test_DynAny::run_test (void)
{
  Data data (this->orb_);

  try
    {
      CORBA::Object_var factory_obj =
        this->orb_->resolve_initial_references ("DynAnyFactory");

      DynamicAny::DynAnyFactory_var dynany_factory =
        DynamicAny::DynAnyFactory::_narrow (factory_obj.in ());

      if (CORBA::is_nil (dynany_factory.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Nil dynamic any factory after narrow\n"),
                            -1);
        }

      DynAnyAnalyzer analyzer (this->orb_.in (),
                               dynany_factory.in (),
                               debug_);
      {
        ACE_DEBUG ((LM_DEBUG,
                    "\t*=*=*=*= %C =*=*=*=*\n",
                    data.labels[8]));

        ACE_DEBUG ((LM_DEBUG,
                    "testing: constructor(Any)/insert/get\n"));

        CORBA::Any in1;
        in1 <<= data.m_double2;
        DynamicAny::DynAny_var fa1 =
          dynany_factory->create_dyn_any (in1);

        if (fa1->equal(fa1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ACE_DEBUG ((LM_DEBUG,
                        "Double Not equal\n"));
            ++this->error_count_;
          }
        fa1->insert_double (data.m_double1);

        CORBA::Double d_out =
          fa1->get_double ();

        if (ACE::is_equal (d_out, data.m_double1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ++this->error_count_;
          }

        ACE_DEBUG ((LM_DEBUG,
                    "testing: constructor(TypeCode)/from_any/to_any\n"));

        d_out = data.m_double2;
        DynamicAny::DynAny_var ftc1 =
          dynany_factory->create_dyn_any_from_type_code (CORBA::_tc_double);
        CORBA::Any in_any1;
        in_any1 <<= data.m_double1;
        ftc1->from_any (in_any1);
        analyzer.analyze (ftc1.in());
        CORBA::Any_var out_any1 = ftc1->to_any ();
        out_any1 >>= d_out;

        if (ACE::is_equal (d_out, data.m_double1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ++this->error_count_;
          }

        fa1->destroy ();
        ftc1->destroy ();
      }

      {
        ACE_DEBUG ((LM_DEBUG,
                    "\t*=*=*=*= %C =*=*=*=*\n",
                    data.labels[17]));

        ACE_DEBUG ((LM_DEBUG,
                    "testing: constructor(Any)/insert/get\n"));

        CORBA::Any in1;
        in1 <<= data.m_longdouble2;
        DynamicAny::DynAny_var fa1 =
          dynany_factory->create_dyn_any (in1);

        if (fa1->equal(fa1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ACE_DEBUG ((LM_DEBUG,
                        "Long Double Not equal\n"));
            ++this->error_count_;
          }

        fa1->insert_longdouble (data.m_longdouble1);

        CORBA::LongDouble d_out = fa1->get_longdouble ();

        if (ACE::is_equal (d_out, data.m_longdouble1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ++this->error_count_;
          }

        ACE_DEBUG ((LM_DEBUG,
                    "testing: constructor(TypeCode)/from_any/to_any\n"));

        d_out = data.m_longdouble2;
        DynamicAny::DynAny_var ftc1 =
          dynany_factory->create_dyn_any_from_type_code (CORBA::_tc_longdouble);

        CORBA::Any in_any1;
        in_any1 <<= data.m_longdouble1;
        ftc1->from_any (in_any1);

        analyzer.analyze(ftc1.in());

        CORBA::Any_var out_any1 = ftc1->to_any ();

        out_any1.in() >>= d_out;

        if (ACE::is_equal (d_out, data.m_longdouble1))
          {
            ACE_DEBUG ((LM_DEBUG,
                        "++ OK ++\n"));
          }
        else
          {
            ++this->error_count_;
          }

        fa1->destroy ();
        ftc1->destroy ();
      }

      ACE_DEBUG ((LM_DEBUG,
                  "\t*=*=*=*= %C =*=*=*=*\n",
                  data.labels[12]));

      ACE_DEBUG ((LM_DEBUG,
                  "testing: constructor(Any)/insert/get\n"));

      CORBA::Any in;
      in <<= data.m_typecode2;
      DynamicAny::DynAny_var fa2 =
        dynany_factory->create_dyn_any (in);
      fa2->insert_typecode (data.m_typecode1);
      CORBA::TypeCode_var tc_out =
        fa2->get_typecode ();

      if (tc_out->equal (data.m_typecode1))
        {
          ACE_DEBUG ((LM_DEBUG,
                      "++ OK ++\n"));
        }
      else
        {
          ++this->error_count_;
        }


      ACE_DEBUG ((LM_DEBUG,
                  "testing: constructor(TypeCode)/from_any/to_any\n"));

      DynamicAny::DynAny_var ftc2 =
        dynany_factory->create_dyn_any_from_type_code (CORBA::_tc_TypeCode);
      CORBA::Any in_any2;
      in_any2 <<= data.m_typecode1;
      ftc2->from_any (in_any2);
      analyzer.analyze (ftc2.in());
      CORBA::Any_var out_any2 = ftc2->to_any ();
      CORBA::TypeCode_ptr out_tc;
      out_any2 >>= out_tc;

      CORBA::Boolean equal = out_tc->equal (data.m_typecode1);

      if (equal)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "++ OK ++\n"));
        }
      else
        {
          ++this->error_count_;
        }


      fa2->destroy ();
      ftc2->destroy ();

      ACE_DEBUG ((LM_DEBUG,
                  "\t*=*=*=*= %C =*=*=*=*\n",
                  data.labels[16]));

      ACE_DEBUG ((LM_DEBUG,
                  "testing: constructor(Any)/insert/get\n"));

      CORBA::Any in3;
      CORBA::ShortSeq ss;
      ss.length (0UL);
      in3 <<= ss;
      DynamicAny::DynAny_var fa3 =
        dynany_factory->create_dyn_any (in3);
      fa3->insert_short_seq (data.m_shortseq1);
      data.m_shortseq2 =
        fa3->get_short_seq ();

      bool good =
        data.m_shortseq2->length () == data.m_shortseq1.length ();

      if (good)
        {
          for (CORBA::ULong i = 0; i < data.m_shortseq1.length (); ++i)
            {
              if (data.m_shortseq2[i] != data.m_shortseq1[i])
                {
                  good = false;
                  break;
                }
            }
        }

      if (good)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "++ OK ++\n"));
        }
      else
        {
          ++this->error_count_;
        }


      ACE_DEBUG ((LM_DEBUG,
                  "testing: constructor(TypeCode)/from_any/to_any\n"));

      DynamicAny::DynAny_var ftc3 =
        dynany_factory->create_dyn_any_from_type_code (CORBA::_tc_ShortSeq);
      CORBA::Any in_any3;
      in_any3 <<= data.m_shortseq1;
      ftc3->from_any (in_any3);
      analyzer.analyze (ftc3.in ());
      CORBA::Any_var out_any3 = ftc3->to_any ();

      CORBA::ShortSeq *outseq = 0;
      out_any3.in () >>= outseq;

      good =
        outseq->length () == data.m_shortseq1.length ();

      if (good)
        {
          for (CORBA::ULong i = 0; i < data.m_shortseq1.length (); ++i)
            {
              if ((*outseq)[i] != data.m_shortseq1[i])
                {
                  good = false;
                  break;
                }
            }
        }

      if (good)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "++ OK ++\n"));
        }
      else
        {
          ++this->error_count_;
        }

      fa3->destroy ();
      ftc3->destroy ();

      ACE_DEBUG ((LM_DEBUG,
                  "testing: equal\n"));

      // Simple equal to self test for basic sequence
      // Check equal to self, not equal for different length
      // not equal for different values
      CORBA::Any in4;
      in4 <<= data.m_shortseq1;
      DynamicAny::DynAny_var fa4 =
        dynany_factory->create_dyn_any (in4);

      // is equal to self
      good = fa4->equal(fa4);

      CORBA::ShortSeq ss5;
      ss5.length(1);
      ss5[0] = 5;
      CORBA::Any in5;
      in5 <<= ss5;
      DynamicAny::DynAny_var fa5 =
        dynany_factory->create_dyn_any (in5);

      // is not equal for different lengths
      good = good && !fa4->equal(fa5);

      CORBA::ShortSeq ss6(data.m_shortseq1);
      ss6[0]++;
      CORBA::Any in6;
      in6 <<= ss6;

      DynamicAny::DynAny_var fa6 =
        dynany_factory->create_dyn_any (in6);

      // is not equal for different values
      good = good && !fa4->equal(fa6);


      CORBA::Any in7;
      in7 <<= data.m_shortseq1;
      DynamicAny::DynAny_var fa7 =
        dynany_factory->create_dyn_any (in7);


      // is equal to identical sequence, not self
      good = good && fa4->equal(fa7);


      if (good)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "++ OK ++\n"));
        }
      else
        {
          ++this->error_count_;
        }

    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("test_dynany::run_test");
      ++this->error_count_;
    }

  ACE_DEBUG ((LM_DEBUG,
              "\n%d errors\n",
              this->error_count_));

  return error_count_;
}
示例#23
0
文件: server.cpp 项目: CCJY/ATCD
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int priority =
    (ACE_Sched_Params::priority_min (ACE_SCHED_FIFO)
     + ACE_Sched_Params::priority_max (ACE_SCHED_FIFO)) / 2;
  priority = ACE_Sched_Params::next_priority (ACE_SCHED_FIFO,
                                              priority);
  // Enable FIFO scheduling, e.g., RT scheduling class on Solaris.

  if (ACE_OS::sched_params (ACE_Sched_Params (ACE_SCHED_FIFO,
                                              priority,
                                              ACE_SCOPE_PROCESS)) != 0)
    {
      if (ACE_OS::last_error () == EPERM)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "server (%P|%t): user is not superuser, "
                      "test runs in time-shared class\n"));
        }
      else
        ACE_ERROR ((LM_ERROR,
                    "server (%P|%t): sched_params failed\n"));
    }

  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      CORBA::Object_var poa_object =
        orb->resolve_initial_references("RootPOA");

      if (CORBA::is_nil (poa_object.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Unable to initialize the POA.\n"),
                          1);

      PortableServer::POA_var root_poa =
        PortableServer::POA::_narrow (poa_object.in ());

      PortableServer::POAManager_var poa_manager =
        root_poa->the_POAManager ();

      if (parse_args (argc, argv) != 0)
        return 1;

      Roundtrip *roundtrip_impl;
      ACE_NEW_RETURN (roundtrip_impl,
                      Roundtrip (orb.in ()),
                      1);
      PortableServer::ServantBase_var owner_transfer(roundtrip_impl);

      PortableServer::ObjectId_var id =
        root_poa->activate_object (roundtrip_impl);

      CORBA::Object_var object = root_poa->id_to_reference (id.in ());

      Test::Roundtrip_var roundtrip =
        Test::Roundtrip::_narrow (object.in ());

      CORBA::String_var ior =
        orb->object_to_string (roundtrip.in ());

      // If the ior_output_file exists, output the ior to it
      FILE *output_file= ACE_OS::fopen (ior_output_file, "w");
      if (output_file == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot open output file for writing IOR: %s",
                           ior_output_file),
                          1);
      ACE_OS::fprintf (output_file, "%s", ior.in ());
      ACE_OS::fclose (output_file);

      poa_manager->activate ();

      Worker_Thread worker (orb.in ());

      worker.activate (THR_NEW_LWP | THR_JOINABLE, 4, 1);
      worker.thr_mgr ()->wait ();

      ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n"));

      root_poa->destroy (1, 1);

      orb->destroy ();
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught:");
      return 1;
    }

  return 0;
}
示例#24
0
文件: server.cpp 项目: OspreyHub/ATCD
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      CORBA::Object_var poa_object =
        orb->resolve_initial_references("RootPOA");

      PortableServer::POA_var root_poa =
        PortableServer::POA::_narrow (poa_object.in ());
      if (CORBA::is_nil (root_poa.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Unable to initialize the POA.\n"),
                          1);

      PortableServer::POAManager_var poa_manager =
        root_poa->the_POAManager ();

      if (parse_args (argc, argv) != 0)
        return 1;

      Simple_Server_i server_impl (orb.in ());

      PortableServer::ObjectId_var id =
        root_poa->activate_object (&server_impl);

      CORBA::Object_var object = root_poa->id_to_reference (id.in ());

      Simple_Server_var server =
        Simple_Server::_narrow (object.in ());

      CORBA::String_var ior =
        orb->object_to_string (server.in ());

      CORBA::Object_var table_object =
        orb->resolve_initial_references("IORTable");

      IORTable::Table_var table =
        IORTable::Table::_narrow (table_object.in ());
      if (CORBA::is_nil (table.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Unable to initialize the IORTable.\n"),
                          1);
      table->bind ("Simple_Server", ior.in ());

      ACE_DEBUG ((LM_DEBUG, "Activated as <%C>\n", ior.in ()));

      FILE *output_file= ACE_OS::fopen (ior_output_file, "w");
      if (output_file == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot open output file for writing IOR: %s",
                           ior_output_file),
                          1);
      ACE_OS::fprintf (output_file, "%s", ior.in ());
      ACE_OS::fclose (output_file);

      poa_manager->activate ();

      orb->run ();

      ACE_DEBUG ((LM_DEBUG, "event loop finished\n"));
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught:");
      return 1;
    }

  return 0;
}
示例#25
0
文件: server.cpp 项目: CCJY/ATCD
int
loadNotify(ACE_Service_Config & service_config)
{
  try
  {
    DllOrb * p_orb = ACE_Dynamic_Service<DllOrb>::instance ("testDllOrb");
    CORBA::ORB_var v_orb = p_orb->orb();

    CORBA::Object_var v_poa = v_orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var v_rootPOA = PortableServer::POA::_narrow(v_poa.in ());
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("RootPOA OK.\n")));

    ACE_DEBUG ((LM_INFO, ACE_TEXT ("Loading NotifyService ...\n")));
    if(0 != service_config.process_directive(scpc_loadNotifyService))
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("Loading NotifyService failed\n")));
      return -1;
    }
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("Loading NotifyService done.\n")));

    TAO_CosNotify_Service * p_notifyService =
      ACE_Dynamic_Service<TAO_CosNotify_Service>::instance("testNotifyService");

    p_notifyService->init_service(v_orb.in());

    CosNotifyChannelAdmin::EventChannelFactory_var v_notifyFactory =
      p_notifyService->create(
        v_rootPOA.in()
      );
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("got EventChannelFactory\n")));

    // create an event channel
    CosNotifyChannelAdmin::ChannelID id;

    CosNotification::QoSProperties initialQos;
    CosNotification::AdminProperties initialAdmin;

    CosNotifyChannelAdmin::EventChannel_var v_eventChannel =
      v_notifyFactory->create_channel(
        initialQos,
        initialAdmin,
        id
      );
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("got EventChannel\n")));

    CosNotifyFilter::FilterFactory_var v_filterFactory =
      v_eventChannel->default_filter_factory();
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("got FilterFactory\n")));

    CosNotifyFilter::Filter_var v_filter =
      v_filterFactory->create_filter("ETCL");
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("got Filter\n")));
  }
  catch(CORBA::Exception const & rc_ex)
  {
    rc_ex._tao_print_exception ("Unexpected CORBA Exception: ");
    return -1;
  }
  catch(...)
  {
    ACE_ERROR ((LM_ERROR, ACE_TEXT ("Unexpected C++ Exception\n")));
    return -1;
  }

  return 0;
}
void CoAPRDLookUpEPResource::handler_get(CoAPCallback &callback)
{
    std::string ep_result;
    
    find_ep_result(ep_result);

    if (ep_result.empty())
    {
    
        coap_pdu_t *response = (coap_pdu_t*)callback.response_;
        
        /* create response */
        response->hdr->code = COAP_RESPONSE_404;
    }
    else
    {

        unsigned char buf[3];
        std::string result;
        coap_block_t block_opt;
        
        coap_pdu_t *response = (coap_pdu_t*)callback.response_;
        
        /* create response */
        response->hdr->code = COAP_RESPONSE_CODE(205);
        
        coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
                        coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
        
        coap_add_option(response, COAP_OPTION_MAXAGE,
                        coap_encode_var_bytes(buf, 0x2ffff), buf);
                        
        /* 1.if result more than 1024 byte, block wise transfer,
         * otherwise directly transfer
         * 2. if client set block2 option, response must be block-wise transferred
         */
        if (1 == coap_get_block((coap_pdu_t*)callback.request_, COAP_OPTION_BLOCK2, &block_opt))
        {
            ACE_DEBUG((LM_DEBUG, "send data by block from %d(size=%d)\n",block_opt.num,block_opt.szx));

            if (1 == send_data_by_block(response, &block_opt, (unsigned char*)ep_result.c_str(), ep_result.length()))
            {
                return;
            }
        }

        if (ep_result.length() > 1024 )
        {
            block_opt.szx = 6;
            block_opt.m = 1;
            block_opt.num = 0;

            ACE_DEBUG((LM_DEBUG, "send data by block from %d(size=%d)\n",block_opt.num,block_opt.szx));

            if (1 == send_data_by_block(response, &block_opt, (unsigned char*)ep_result.c_str(), ep_result.length()))
            {
                return;
            }            
        }

        /* at here, we send data directly*/
        {
        
            ACE_DEBUG((LM_DEBUG, "send data directly(len=%d)\n", ep_result.length()));
            
            coap_add_data(response, ep_result.length(), (unsigned char*)ep_result.c_str());
        }
    }
    
}
示例#27
0
文件: growth.cpp 项目: OspreyHub/ATCD
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int n = 100;
  int low = 64;
  int hi = 4096;
  int s = 4;
  int quiet = 0;

  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("dn:l:h:s:q"));
  int opt;

  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
        case 'd':
          TAO_debug_level++;
          break;
        case 'n':
          n = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'l':
          low = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'h':
          hi = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 's':
          s = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'q':
          quiet = 1;
          break;
        case '?':
        default:
          ACE_DEBUG ((LM_DEBUG,
                      "Usage: %s "
                      "-d debug"
                      "-l low "
                      "-h high "
                      "-s step "
                      "-n n "
                      "\n"
                      "Writes and then reads longs to a CDR stream "
                      "starting from <low> up to <high> incrementing "
                      "by <step>, at each step run <n> iterations to "
                      "average."
                      "\n",
                      argv[0]));
          return -1;
        }
    }

  for (int x = low; x <= hi; x += s)
    {
      ACE_High_Res_Timer writing;
      ACE_High_Res_Timer reading;
      if (TAO_debug_level > 0)
        ACE_DEBUG ((LM_DEBUG, "\nx= %d\n", x));

      for (int i = 0; i < n; ++i)
        {
          writing.start_incr ();
          TAO_OutputCDR output;

          if (test_write (output, x) != 0)
            {
              return 1;
            }
          writing.stop_incr ();

          reading.start_incr ();
          TAO_InputCDR input (output);
          if (test_read (input, x) != 0)
            {
              return 1;
            }
          reading.stop_incr ();
        }
      double m = n * x;

      ACE_Time_Value wtv;
      writing.elapsed_time_incr (wtv);
      ACE_hrtime_t wusecs = wtv.sec ();
      wusecs *= static_cast<ACE_UINT32> (ACE_ONE_SECOND_IN_USECS);
      wusecs += wtv.usec ();

      ACE_Time_Value rtv;
      reading.elapsed_time_incr (rtv);
      ACE_hrtime_t rusecs = rtv.sec ();
      rusecs *= static_cast<ACE_UINT32> (ACE_ONE_SECOND_IN_USECS);
      rusecs += rtv.usec ();

      double write_average = ACE_HRTIME_CONVERSION(wusecs) / m;
      double read_average = ACE_HRTIME_CONVERSION(rusecs) / m;
      if (!quiet)
        ACE_OS::printf ("AVE: %d %f %f\n",
                        x, write_average, read_average);
    }
  return 0;
}
示例#28
0
文件: server.cpp 项目: colding/lorica
int
main (int argc, char *argv[])
{
  try
    {
      // Create the ORB initializer.
      Server_ORBInitializer *temp_initializer = 0;
      ACE_NEW_RETURN (temp_initializer,
                      Server_ORBInitializer,
                      -1);

      PortableInterceptor::ORBInitializer_var initializer =
        temp_initializer;

      PortableInterceptor::register_orb_initializer (initializer.in ());

      // Now initialize the ORB.
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "");
      CORBA::Object_var poa_object =
				orb->resolve_initial_references("RootPOA");

      if (CORBA::is_nil (poa_object.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
			     " (%P|%t) Unable to initialize the POA.\n"),
			    1);
        }

      PortableServer::POA_var root_poa =
	      PortableServer::POA::_narrow (poa_object.in ());

      PortableServer::POAManager_var poa_manager =
	      root_poa->the_POAManager ();

      if (parse_args (argc, argv) != 0)
        {
           return 1;
        }

			// Create the interceptor.
			ForwardTest_Request_Interceptor * server_interceptor =
				temp_initializer->server_interceptor();

      // getting the original oject
      Forward_Test_i *final_impl = new Forward_Test_i(orb.in ());
      PortableServer::ServantBase_var servant = final_impl;
      Forward::Test_var target = final_impl->_this ();

			server_interceptor->forward_reference (target.in());

			Forward_Test_i *server_impl = new Forward_Test_i (orb.in());
      servant = server_impl;
      Forward::Test_var server = server_impl->_this ();

      // getting the mapper object
      CORBA::Object_var obj =
	      orb->string_to_object (lorica_ior);
      Lorica::ReferenceMapper_var mapper =
	      Lorica::ReferenceMapper::_narrow(obj.in());
      if (CORBA::is_nil(mapper.in()))
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Cannot get reference to Lorica "
				 "reference mapper\n"),1);

      // getting the mapped object
      obj = mapper->as_server(server.in(),"ForwardTest",
			      Lorica::ServerAgent::_nil());
      if (CORBA::is_nil (obj.in()))
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Lorica reference mapper returned a nil "
				 "mapped reference.\n"),1);

      // narrowing the mapped object
      Forward::Test_var h2 = Forward::Test::_narrow(obj.in());
      if (CORBA::is_nil(h2.in()))
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Lorica reference mapper returned an "
				 "incorrectly typed reference\n"),1);


      CORBA::String_var orig_ior =
	      orb->object_to_string (server.in ());
      CORBA::String_var mapped_ior =
	      orb->object_to_string (h2.in());

      if (ACE_OS::strcmp (orig_ior.in(), mapped_ior.in()) == 0)
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Lorica reference mapper returned "
				 "the original reference unmapped.\n"),1);

      ACE_DEBUG ((LM_DEBUG,"writing original IOR to file %s\n",orig_file));
      ACE_DEBUG ((LM_DEBUG,"writing mapped IOR to file %s\n",mapped_file));
      ACE_DEBUG ((LM_DEBUG,"Size of orig IOR = %d, size of mapped = %d\n",
		  ACE_OS::strlen(orig_ior.in()),
		  ACE_OS::strlen(mapped_ior.in())));

      FILE *output_file= ACE_OS::fopen (mapped_file, "w");
      if (output_file == 0)
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Cannot open output file for writing IOR: %s\n",
				 mapped_file),
				1);
      ACE_OS::fprintf (output_file, "%s", mapped_ior.in());
      ACE_OS::fclose (output_file);

      output_file= ACE_OS::fopen (orig_file, "w");
      if (output_file == 0)
	      ACE_ERROR_RETURN ((LM_ERROR,
				 "Cannot open output file for writing IOR: %s\n",
				 orig_file),
				1);
      ACE_OS::fprintf (output_file, "%s", orig_ior.in());
      ACE_OS::fclose (output_file);

      poa_manager->activate ();

      orb->run ();

      ACE_DEBUG ((LM_DEBUG, "event loop finished\n"));
    }
  catch (const CORBA::Exception& ex)
	  {
		  ex._tao_print_exception ("Server: exception caught - ");
		  return 1;
	  }

  return 0;
}
示例#29
0
// sets up the dataModeSocket Stream, reads the test header infomation
// and launches a thread to handle the requested test.
static void run_server (ACE_HANDLE handle)
{
  ACE_INET_Addr cli_addr;
  // create a new stream and initialized with the handle returned by
  // accept
  ACE_SOCK_Stream * dataModeStream = new ACE_SOCK_Stream;
  dataModeStream->set_handle (handle);

  // Make sure we're not in non-blocking mode.
  if (dataModeStream->disable (ACE_NONBLOCK) == -1){
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("disable")));
    return;
  }
  else if (dataModeStream->get_remote_addr (cli_addr) == -1){
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("get_remote_addr")));
    return;
  }

  // explicity configure Nagling. Default is
  // Options_Manager::test_enable_nagle=0 so default configurations is
  // NO NAGLING
  ACE_CDR::Long nagle;
  if (Options_Manager::test_enable_nagle)
    nagle=0;
  else
    nagle=1;

  if (Options_Manager::test_transport_protocol == IPPROTO_SCTP){
    // default - sctp case
    if (-1 == dataModeStream->set_option(IPPROTO_SCTP, SCTP_NODELAY, &nagle, sizeof nagle)){
      ACE_ERROR((LM_ERROR,
                 ACE_TEXT ("%p\n"),
                 ACE_TEXT ("set_option")));
      return;
    }
  } else {
    // tcp case
    if (-1 == dataModeStream->set_option(IPPROTO_TCP, TCP_NODELAY, &nagle, sizeof nagle)){
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "set_option"));
      return;
    }
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) client %C connected from %d\n"),
              cli_addr.get_host_name (),
              cli_addr.get_port_number ()));

  // hdr bufSize is hardcoded to 8 bytes
  // (4 for a CDR-encoded boolean and 4 for a CDR-encoded ULong)
  ACE_CDR::ULong hdrBufSize = 8;
  // allocate a raw buffer large enough to receive the header and be
  // properly aligned for the CDR decoding.
  ACE_CDR::Char * hdrBuf= new ACE_CDR::Char[hdrBufSize+ACE_CDR::MAX_ALIGNMENT];
  // align the raw buffer before reading data into it.
  char * hdrBuf_a = ACE_ptr_align_binary(hdrBuf, ACE_CDR::MAX_ALIGNMENT);

  size_t bt;
  // read the header
  if ((dataModeStream->recv_n(hdrBuf_a, hdrBufSize, 0, &bt)) == -1){
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("recv_n")));
    return;
  }

  // pass the CDR encoded data into an ACE_InputCDR class. hdrCDR does
  // NOT copy this data. Nor does it delete. It assumes the buffer
  // remains valid while it is in scope.
  ACE_InputCDR hdrCDR(hdrBuf_a, hdrBufSize);

  ACE_CDR::Boolean byteOrder;
  ACE_CDR::ULong numIterations;

  // extract the data
  hdrCDR >> ACE_InputCDR::to_boolean (byteOrder);
  hdrCDR.reset_byte_order(byteOrder);
  hdrCDR >> numIterations;

  // make sure the stream is good after the extractions
  if (!hdrCDR.good_bit()){
    ACE_ERROR((LM_ERROR,
               ACE_TEXT ("%p\n"),
               ACE_TEXT ("hdrCDR")));

    return;
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) Test for %u iterations\n"),
              numIterations));

  // deallocate the header buffer
  delete[] hdrBuf;

  // bundle up the arguments
  ArgStruct * args = new ArgStruct;
  args->stream = dataModeStream;
  args->numIters = numIterations;

#if defined (ACE_HAS_THREADS)
  // Spawn a new thread and run the new connection in that thread of
  // control using the <server> function as the entry point.
  if (ACE_Thread_Manager::instance ()->spawn (unmarshalledOctetServer,
                                              reinterpret_cast<void *> (args),
                                              THR_DETACHED) == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) %p\n"),
                ACE_TEXT ("spawn")));
#else
  (*unmarshalledOctetServer) (reinterpret_cast<void *> (args));
#endif /* ACE_HAS_THREADS */

}
void
RPG_Graphics_Cursor_Manager::updateHighlightBG(const RPG_Graphics_Position_t& viewPort_in, 
											   SDL_Rect& dirtyRegion_out,
											   const SDL_Rect* clipRectangle_in,
											   const bool& lockedAccess_in,
											   const bool& debug_in)
{
	RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::updateHighlightBG"));

	// sanity check(s)
	ACE_ASSERT(myHighlightWindow);
	SDL_Surface* target_surface = myHighlightWindow->getScreen();
	ACE_ASSERT(target_surface);

	// init return value(s)
	ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out));

	SDL_Rect window_area, clip_area, clip_rectangle, source_clip_rectangle;
	myHighlightWindow->getArea(window_area, true);
	myHighlightWindow->getArea(clip_area, false);
	if (clipRectangle_in)
		clip_area = *clipRectangle_in;
	RPG_Graphics_Position_t screen_position;
	SDL_Surface* new_background = NULL;
	if (myScreenLock && lockedAccess_in && debug_in)
		myScreenLock->lock();
	for (RPG_Graphics_TileCacheIterator_t iterator = myHighlightBGCache.begin();
			 iterator != myHighlightBGCache.end();
			 iterator++)
	{
		screen_position =
			RPG_Graphics_Common_Tools::map2Screen((*iterator).first,
												  std::make_pair(window_area.w,
																 window_area.h),
												  viewPort_in);
		source_clip_rectangle.x = screen_position.first;
		source_clip_rectangle.y = screen_position.second;
		source_clip_rectangle.w = (*iterator).second->w;
		source_clip_rectangle.h = (*iterator).second->h;
		clip_rectangle = RPG_Graphics_SDL_Tools::intersect(clip_area,
														   source_clip_rectangle);
		if (!clip_rectangle.w || !clip_rectangle.h)
			continue; // nothing to do...

		if ((clip_rectangle.w == (*iterator).second->w) &&
			(clip_rectangle.h == (*iterator).second->h))
		{
			// cached highlight bg completely "dirty"
			// --> just get a fresh copy
			RPG_Graphics_Surface::get(screen_position,
									  true, // use (fast) blitting method
									  *target_surface,
									  *(*iterator).second);

			// debug info
			if (debug_in)
			{
				// show bg surface in left upper corner
				ACE_ASSERT(target_surface->w >= (*iterator).second->w);
				ACE_ASSERT(target_surface->h >= (*iterator).second->h);

				// compute bounding box
				SDL_Rect dirty_region;
				dirty_region.x = target_surface->w - (*iterator).second->w;
				dirty_region.y = target_surface->h - (*iterator).second->h;
				dirty_region.w = (*iterator).second->w;
				dirty_region.h = (*iterator).second->h;

				RPG_Graphics_Surface::put(std::make_pair(dirty_region.x,
													 	 dirty_region.y),
									      *(*iterator).second,
										  target_surface,
										  dirty_region);
				dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(dirty_region,
														 		      dirtyRegion_out);
			} // end IF

			continue;
		} // end IF

		// get a fresh copy from that part of the map
		new_background =
			RPG_Graphics_Surface::create(static_cast<unsigned int>((*iterator).second->w),
										 static_cast<unsigned int>((*iterator).second->h));
		if (!new_background)
		{
			ACE_DEBUG((LM_ERROR,
					   ACE_TEXT("failed to RPG_Graphics_Surface::create(%u,%u), continuing\n"),
					   (*iterator).second->w, (*iterator).second->h));

			continue;
		} // end IF
		RPG_Graphics_Surface::get(screen_position,
								true, // use (fast) blitting method
								*target_surface,
								*new_background);

		// mask the "dirty" bit of the cached bg
		// --> adjust intersection coordinates (relative to cached bg surface)
		clip_rectangle.x -= screen_position.first;
		clip_rectangle.y -= screen_position.second;
		if (SDL_FillRect((*iterator).second,
			               &clip_rectangle,
										 RPG_Graphics_SDL_Tools::getColor(COLOR_BLACK_A0, // transparent
										                                  *(*iterator).second)))
		{
			ACE_DEBUG((LM_ERROR,
								 ACE_TEXT("failed to SDL_FillRect(): \"%s\", continuing\n"),
								 ACE_TEXT(SDL_GetError())));

			// clean up
			SDL_FreeSurface(new_background);

			continue;
		} // end IF

		// blit the cached/masked bg onto the fresh copy
		if (SDL_BlitSurface((*iterator).second, // source
												NULL,               // aspect (--> everything)
												new_background,     // target
												NULL))              // aspect (--> everything)
		{
			ACE_DEBUG((LM_ERROR,
								 ACE_TEXT("failed to SDL_BlitSurface(): %s, continuing\n"),
								 ACE_TEXT(SDL_GetError())));

			// clean up
			SDL_FreeSurface(new_background);

			continue;
		} // end IF

		// clean up
		SDL_FreeSurface((*iterator).second);

		(*iterator).second = new_background;

		// debug info
		if (debug_in)
		{
			// show bg surface in left upper corner
			ACE_ASSERT(target_surface->w >= (*iterator).second->w);
			ACE_ASSERT(target_surface->h >= (*iterator).second->h);

			// compute bounding box
			SDL_Rect dirty_region;
			dirty_region.x = 0;
			dirty_region.y = 0;
			dirty_region.w = (*iterator).second->w;
			dirty_region.h = (*iterator).second->h;

			RPG_Graphics_Surface::put(std::make_pair(dirty_region.x,
																							 dirty_region.y),
																*(*iterator).second,
																target_surface,
																dirty_region);
			dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(dirty_region,
																														dirtyRegion_out);
		} // end IF
	} // end FOR
	if (myScreenLock && lockedAccess_in && debug_in)
		myScreenLock->unlock();
}