Exemplo n.º 1
0
 ACE_CATCH (CORBA::UserException, userex)
   {
     ACE_PRINT_EXCEPTION (userex, "User Exception :");
     qms_api.connect_supplier();
     qms_api.connect_consumer();
     exit (2);
   }
Exemplo n.º 2
0
 ACE_CATCH (CORBA::DATA_CONVERSION, ex)
 {
     ACE_PRINT_EXCEPTION(ex,
             "Most likely, this is due to the in-ability "
             "to set the thread priority.");
     return -1;
 }
Exemplo n.º 3
0
    ACE_CATCH (CORBA::UserException, userex)
      {
	ACE_PRINT_EXCEPTION (userex, 
			     "User Exception initializing EC_Adapter:");
	this->disconnect();
	ACE_RE_THROW;
      }
Exemplo n.º 4
0
 ACE_CATCH (CORBA::SystemException, sysex)
 {
     ACE_PRINT_EXCEPTION (sysex, "System Exception :");
     cerr << "ID = " << sysex._id() << "; minor code = " << sysex.minor()
      << endl;
       //ACE_RE_THROW;
 }
Exemplo n.º 5
0
/**
 * @brief This function handles import operation on TAO Trading  Service.
 * @param argc Number of command line arguments
 * @param argv[] Holds the Command lines arguments in character array.
 * @return Returns an integer.
 *
 *   The main function performs the following operations.
 * 
 * 1:- Creates an instance of CORBA Handles  and initializes it.
 * 2:- Gets the reference to orb from the handles.
 * 3:- Gets reference to trading_service and narrows it to Lookup interface.
 * 4:- Queries the trading service and gets the reference to QMS_Trader_ECInfo .
 * 5:- Executes either the Event channel related methods or get_supplier_id method
 *     depending on the command line option.
 * 6:- Throws exceptions if any of the operation fails.
 */
int
main (int argc, char** argv)
{
  /// Variables for holding the qms unique category and supplier names.
  char *qms_unique_name=0, *supplier_name=0;

 /// Variables for holding the information about Announce, Data and Request
 /// Channel for a given qms unique category name.
  STDC::QMS::Citizen::QMS_Trader_ECInfo::AnnounceSeq *ImportAECSeq = 0;
  STDC::QMS::Citizen::QMS_Trader_ECInfo::DataSeq * ImportDECSeq = 0;
  STDC::QMS::Citizen::QMS_Trader_ECInfo::RequestSeq * ImportRECSeq = 0;

  /// Installing the signal handlers.
  signal(SIGTERM,sig_handler);
  signal(SIGINT,sig_handler);
  signal(SIGABRT,sig_handler);
  signal(SIGHUP,sig_handler);
  signal(SIGSEGV,sig_handler);

   DEBUG0 (DEBUG_L_CALL, "DEBUG: parsing arguments\n");
   for (int i = 0; i < argc; i++)
   {
     if (!argv[i])           { break; }
     if (argv[i][0] != '-')  { continue; }
     int j = 1;
     if (argv[i][1] == '-')  {
       if (argv[i][2] == 0)  { break; }// handle -- end of options
       j = 2;// handle --argument
     }
     if (strstr((argv[i] + j), "ORB"))  { continue; }
     if (! strcmp((argv[i] + j), "help") || strchr((argv[i] + j), 'h'))
      {// -h or --help
            cerr << argv[0] << version << endl
           << "Usage: " << argv[0] << "[CORBA OPTIONS] [OPTIONS]"
           << endl
           << "\t-h             : This help text"  << endl
           << "\t-v             : Prints out the version"  << endl
           << "\t-q qms_unique_name  : "  << endl
           << "\t OR                   "  << endl
           << "\t-n supplier_name    : "  << endl;
            exit (0);
      }
     if (! strcmp((argv[i] + j), "version") || strchr((argv[i] + j), 'v'))
      {
          cerr << argv[0] << ": Version "<< version << endl;
          exit (0);
      }
     if (strchr((argv[i] + j), 'q'))
      {
          qms_unique_name = (char *) malloc (strlen(argv[i + 1]) + 1);
          strcpy(qms_unique_name,argv[i + 1]);
          continue;
      }
     if (strchr((argv[i] + j), 'n'))
      {
          supplier_name = (char *) malloc (strlen(argv[i + 1]) + 1);
          strcpy(supplier_name,argv[i + 1]);
          continue;
      }

   }


  ACE_DECLARE_NEW_CORBA_ENV;
  ACE_TRY
  {
  
      DEBUG0 (DEBUG_L_CALL," Initializing the Corba Handles \n");
      STDC::QMS::CORBA_Handles *handles_p = new STDC::QMS::CORBA_Handles();
      handles_p->init(argc, argv, "Client", ACE_TRY_ENV);
      ACE_TRY_CHECK;


      CosTrading::Lookup_var lookup_v = 
                          handles_p->get_lookup_handle(ACE_TRY_ENV);
      ACE_TRY_CHECK;
      CosTrading::Lookup_ptr lookup_p = lookup_v.in();
      ACE_TRY_CHECK;
      assert(lookup_p);
      assert(!CORBA::is_nil(lookup_p));
      DEBUG0 (DEBUG_L_CALL,"Got the ptr to the lookup interface\n");

      // Now doing an import operation
      PolicySeq policies; //empty sequence
      Lookup::SpecifiedProps desired_props;
      desired_props._d(Lookup::all);
      PolicyNameSeq_var policies_applied; // out param
  
      CosTrading::OfferSeq *offer_seq_ptr = 0;
      CosTrading::OfferSeq_out offer_seq_out (offer_seq_ptr);
      OfferIterator_var iterator;     // out param

      //Run the query without preferences using the default policies
      //changed the iterator to offer_iterator_out and how many to zero 
      //instead of 1

      lookup_p->query(YP_SERVICE_TYPE, "QMS_UNIQ_NAME_CATEGORY == 'QMS_TRADER' ", "", policies, desired_props, 1, 
                                  offer_seq_out, iterator, policies_applied);
      ACE_TRY_CHECK;

     //process the results
     STDC::QMS::Citizen::QMS_Trader_ECInfo_var ecinfo_var;
     const CosTrading::OfferSeq& offer_seq = *offer_seq_ptr;

     if ( offer_seq.length() == 0) 

          ACE_DEBUG ((LM_DEBUG, "No matching service offer\n"));
     else 
     {
       // extract the EventChannelInfo reference from the returned offer.
       ecinfo_var = STDC::QMS::Citizen::QMS_Trader_ECInfo::_narrow(offer_seq[0].reference);
       ACE_TRY_CHECK;
       if (CORBA::is_nil(ecinfo_var))
            DEBUG0 (DEBUG_L_CALL,"The reference is not of type QMS_Trader_ECInfo\n"); 
     }

    // Clean up the iterator
    if (!CORBA::is_nil(iterator))
    {
        iterator->destroy();
        ACE_TRY_CHECK;
    }


    if (supplier_name)
    {
      //get the supplier id using the supplier_name
      cerr << "The Supplier id is -> " << ecinfo_var->getSupplierID(supplier_name) 
      << endl;
    }
    else if (qms_unique_name)
    {

      // use the STDC reference now to invoke the getID operation
      ImportAECSeq = ecinfo_var->getAnnounceChannels(qms_unique_name );
      ACE_TRY_CHECK;

      ImportDECSeq = ecinfo_var->getDataChannels(qms_unique_name );
      ACE_TRY_CHECK;

      ImportRECSeq = ecinfo_var->getRequestChannels(qms_unique_name );
      ACE_TRY_CHECK;

      if ( ImportAECSeq != NULL )
      {
        DEBUG0 (DEBUG_L_CALL,"Got some Announce Channels\n");

        DEBUG1(DEBUG_L_ENTER, "Length of ImportAECSeq ->%d\n", 
                                              ImportAECSeq->length() );
        for (CORBA::ULong i =0; i < ImportAECSeq->length() ; i++)

                cerr << (const char *) (*ImportAECSeq)[i].EventChannelName  
                     << "\t\t" 
                     << (*ImportAECSeq)[i].EventId << endl;

      }

      else
      {
        cerr << "UNABLE to get response from Objectfor Announce Channels \n" ;
      }

      if ( ImportDECSeq != NULL )
      {
        DEBUG0 (DEBUG_L_CALL,"Got some Data Channels\n");

        DEBUG1(DEBUG_L_ENTER, "Length of ImportDECSeq->%d\n", 
                                               ImportDECSeq->length() );

        for (CORBA::ULong i =0; i < ImportDECSeq->length() ; i++)

                cerr << (const char *) (*ImportDECSeq)[i].EventChannelName  
                     << "\t\t" 
                     << (*ImportDECSeq)[i].EventId << endl;

      }

      else
      {
          cerr << "UNABLE to get response from Object for Data Channels\n" ;
      }

      if ( ImportRECSeq != NULL )
      {
        DEBUG0 (DEBUG_L_CALL,"Got some Request Channels\n");

        DEBUG1(DEBUG_L_ENTER, "Length of ImportRECSeq->%d\n", 
                                           ImportRECSeq->length() );

        for (CORBA::ULong i =0; i < ImportRECSeq->length() ; i++)

                cerr << (const char *) (*ImportRECSeq)[i].EventChannelName  
                     << "\t\t" 
                     << (*ImportRECSeq)[i].EventId << endl;

      }

      else
      {
        cerr << "UNABLE to get response from Object for Request Channels\n";
      }

    handles_p->~CORBA_Handles();
    ACE_TRY_CHECK;

    } // for qms_unique_name 
    else {
             cerr << "Pl use -h to see the command line options\n ";

         }
  } // end of ACE_TRY

  ACE_CATCH(CORBA::COMM_FAILURE, commEx)
  {
    ACE_PRINT_EXCEPTION (commEx, "A communication failure occured:");
  }
Exemplo n.º 6
0
 ACE_CATCH(CORBA::NO_PERMISSION, perEx)
 {
   ACE_PRINT_EXCEPTION (perEx, "A no permission failure occured:");
 }
Exemplo n.º 7
0
 ACE_CATCH (CORBA::UserException, userex)
   {
     ACE_PRINT_EXCEPTION (userex, "User Exception :");
     this->disconnect();
     ACE_RE_THROW;
   }
Exemplo n.º 8
0
int
main (int argc, char *argv[])
{
    int c;
    ACE_CString daemonRef;
    ACE_CString hostName;
    for(;;)
        {
        int option_index = 0;
        c = getopt_long (argc, argv, "hd:H:",
                         long_options, &option_index); 
        if (c==-1) break;
        switch(c)
            {
                case 'h':
                    usage(argv[0]);
                    return 0;
                case 'd':
                    daemonRef = optarg;
                    break;
                case 'H':
                    hostName = optarg;
                    break;
            }
        }

	LoggingProxy * logger = new LoggingProxy(0, 0, 31);
	if (logger)
	{
		LoggingProxy::init(logger);
		LoggingProxy::ProcessName(argv[0]);
		LoggingProxy::ThreadName("main");
	}
	else
		ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging."));

	try
	{
		// Initialize the ORB.
		CORBA::ORB_var orb = CORBA::ORB_init (argc,argv,"TAO");

		// construct default one
      if (daemonRef.length() == 0)
	  {
          if(hostName.length() == 0)
          {
	      hostName = ACSPorts::getIP();
          } 
	  daemonRef = "corbaloc::";
	  daemonRef = daemonRef + hostName + ":" + ACSPorts::getContainerDaemonPort().c_str() + "/" + ::acsdaemon::containerDaemonServiceName;	
	  ACS_SHORT_LOG((LM_INFO, "Using local Container Daemon reference: '%s'", daemonRef.c_str()));
	  
	  }
      else
          {
          ACS_SHORT_LOG((LM_INFO, "Container Daemon reference obtained via command line: '%s'", daemonRef.c_str()));
          }


		CORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());
		if (CORBA::is_nil(obj.in()))
		{
			ACS_SHORT_LOG((LM_ERROR, "Failed to resolve reference '%s'.", daemonRef.c_str()));
			return -1;
		}

		acsdaemon::ContainerDaemon_var daemon = acsdaemon::ContainerDaemon::_narrow(obj.in());
		if (CORBA::is_nil(daemon.in()))
		{
			ACS_SHORT_LOG((LM_ERROR, "Failed to narrow reference '%s'.", daemonRef.c_str()));
			return -1;
		}


                ACS_SHORT_LOG((LM_INFO, "Calling shutdown()."));

                daemon->shutdown();

                ACS_SHORT_LOG((LM_INFO, "Daemon shutdown message issued."));


	}
	catch( maciErrType::NoPermissionEx &ex )
	{
		ACS_SHORT_LOG((LM_WARNING, "Daemon is running in protected mode and cannot be shut down remotely!\n"));
		return -1;
	}
	catch( CORBA::Exception &ex )
	{
		ACS_SHORT_LOG((LM_ERROR, "Failed."));
		ACE_PRINT_EXCEPTION (ex, ACE_TEXT ("Caught unexpected exception:"));
		return -1;
	}

	return 0;
}
Exemplo n.º 9
0
/**
 *  @brief The workhorse routine
 *  @param argc The count of the command line arguments
 *  @param argv A pointer to the list of command line arguments
 *  @param ACE_TRY_ENV The CORBA Env variable
 *  @exception CORBA::SystemException
 *
 * This is where the bulk of the work gets done. The sequence of steps is
 *   - The orb is initialized, using the command line options, if any
 *   - The portable Object Adapter is next
 *   - Then we create a POA manager
 *   - The naming service handle is the next
 *   - After the naming context, we get a scheduler handle
 *   - Finally, we get hold of the event channel
 *
 * An overloaded variant exists that provides a similar functionality,
 * except that the event channel handle is deferred until later.
 */
void
STDC::QMS::CORBA_Handles::init (int argc, char **argv, 
				const char * orb_name_p,
				CORBA_Environment &ACE_TRY_ENV)
{
  QMS_Trace ("STDC::QMS::CORBA_Handles::init", __LINE__, __FILE__);
  DEBUG0 (DEBUG_L_ENTER, "DEBUG: QMS  API object initializing\n");
  if(this->_initialized)
   {
     return;
   } /* end of if(this->_initialized) */
  
  ACE_TRY
    {
      // ORB initialization. We shall be using the string QMS_API
      // all through this application
      this->_orb =
	CORBA::ORB_init (argc, argv, orb_name_p, ACE_TRY_ENV);
      ACE_TRY_CHECK;
      if (CORBA::is_nil (this->_orb.in ())){
	ACE_Time_Value sleep_time (QMS_DEFAULT_retry_sleep_interval, 0);
	int count = 0;
	while (CORBA::is_nil (this->_orb.in ())){
	  if (count >= QMS_DEFAULT_number_of_retries){
	    ACE_ERROR ((LM_ERROR,"(%P|%t) Unable to initialize the orb.\n"));
	    ACE_TRY_THROW (CORBA::BAD_PARAM ());
	  }
	  ACE_OS::sleep (sleep_time);
	  DEBUG0 (6, "retrying getting the orb\n");
	  this->_orb =
	    CORBA::ORB_init (argc, argv, "QMS_API", ACE_TRY_ENV);
	  ACE_TRY_CHECK;
	  count++;
	}
      }
      else
       {
	 DEBUG0 (6, "Orb initilized(no external data yet)\n");
       }

      // Ok. The portable Object Adapter is next
      if (CORBA::is_nil (this->_root_poa.in ())){
	CORBA::Object_var poa_object =
	  this->_orb->resolve_initial_references("RootPOA");
	ACE_TRY_CHECK;

	this->_root_poa =
	  PortableServer::POA::_narrow (poa_object.in (), ACE_TRY_ENV);
	ACE_TRY_CHECK;
	DEBUG0 (6, "Narrowed the root poa\n");

	if (CORBA::is_nil (poa_object.in ())){
	  ACE_Time_Value sleep_time (QMS_DEFAULT_retry_sleep_interval, 0);
	  int count = 0;
	  while (CORBA::is_nil (this->_root_poa.in ())){
	    if (count >= QMS_DEFAULT_number_of_retries){
	      ACE_ERROR ((LM_ERROR," Unable to initialize the POA.\n"));
	      ACE_TRY_THROW (CORBA::BAD_PARAM ());
	    }
	    ACE_OS::sleep (sleep_time);
	    DEBUG0 (6, "retrying getting root poa\n");

	    CORBA::Object_var poa_object =
	      this->_orb->resolve_initial_references("RootPOA");
	    ACE_TRY_CHECK;

	    this->_root_poa =
	      PortableServer::POA::_narrow (poa_object.in (), ACE_TRY_ENV);
	    ACE_TRY_CHECK;
	    DEBUG0 (6, "Narrowed the root poa\n");
	    
	    count++;
	  }
	}
	else {
	  DEBUG0 (6, "Got the root poa(no external data yet)\n");
	}
      }
      else
       {
	 DEBUG0 (6, "Already had root poa handle\n");
       }

      // Now we get the manager
      if (CORBA::is_nil (this->_poa_manager.in ())) {
	this->_poa_manager =
	  this->_root_poa->the_POAManager (ACE_TRY_ENV);
	ACE_TRY_CHECK;
	if (CORBA::is_nil (this->_poa_manager.in ())) {
	  ACE_Time_Value sleep_time (QMS_DEFAULT_retry_sleep_interval, 0);
	  int count = 0;
	  while (CORBA::is_nil (this->_poa_manager.in ())){
	    if (count >= QMS_DEFAULT_number_of_retries){
	      ACE_ERROR ((LM_ERROR,"(%P|%t) Unable to get the POA mgr.\n"));
	      ACE_TRY_THROW (CORBA::BAD_PARAM ());
	    }
	    ACE_OS::sleep (sleep_time);
	    DEBUG0 (6, "retrying getting the poa manager\n");

	    this->_poa_manager =
	      this->_root_poa->the_POAManager (ACE_TRY_ENV);
	    ACE_TRY_CHECK;

	    count++;
	  }
	}
	else {
	  DEBUG0(6, "Got the poa manager(no external data yet)\n");
	}
      }
      else
       {
	 DEBUG0 (6, "Already had poa manager handle\n");
       }

      // Obtain a reference to the naming service...
      if (CORBA::is_nil (this->_naming_context.in ())) {
	CORBA::Object_var naming_obj =
	  this->_orb->resolve_initial_references ("NameService", ACE_TRY_ENV);
	ACE_TRY_CHECK;
	this->_naming_context =
	  CosNaming::NamingContext::_narrow (naming_obj.in (), ACE_TRY_ENV);
	ACE_TRY_CHECK;
	DEBUG0 (6, "Narrowed the naming context(Connected)\n");

	if (CORBA::is_nil (this->_naming_context.in())) {
	  ACE_Time_Value sleep_time (QMS_DEFAULT_retry_sleep_interval, 0);
	  int count = 0;
	  while (CORBA::is_nil (this->_naming_context.in ())){
	    if (count >= QMS_DEFAULT_number_of_retries){
	      ACE_ERROR ((LM_ERROR,
			  "(%P|%t) Unable to get the naming context.\n"));
	      ACE_TRY_THROW (CORBA::BAD_PARAM ());
	    }
	    ACE_OS::sleep (sleep_time);
	    DEBUG0 (6, "retrying getting naming context\n");
	    CORBA::Object_var naming_obj =
	      this->_orb->resolve_initial_references ("NameService",
						      ACE_TRY_ENV);
	    ACE_TRY_CHECK;
	    this->_naming_context =
	      CosNaming::NamingContext::_narrow (naming_obj.in (), 
						 ACE_TRY_ENV);
	    ACE_TRY_CHECK;
	    DEBUG0 (6, "Narrowed the naming context(Connected)\n");
	    count++;
	  }
	}
	else {
	  DEBUG0 (6, "Got the naming context(Connected)\n");
	}
      }
      else
       {
	 DEBUG0 (6, "Already Had naming context(Connected)\n");
       }

      // and now for the scheduling service
      if  (CORBA::is_nil (this->_scheduler.in ())) {
	CosNaming::Name schedule_name (1);
	schedule_name.length (1);
	schedule_name[0].id = CORBA::string_dup ("ScheduleService");

	CORBA::Object_var sched_obj=
	  this->_naming_context->resolve (schedule_name, ACE_TRY_ENV);
	ACE_TRY_CHECK;

	this->_scheduler =
	  RtecScheduler::Scheduler::_narrow(sched_obj.in (), ACE_TRY_ENV);
	ACE_TRY_CHECK;
	DEBUG0 (6, "Narrowed  the scheduler handle\n");

	if (CORBA::is_nil (this->_scheduler.in ())) {
	  ACE_Time_Value sleep_time (QMS_DEFAULT_retry_sleep_interval, 0);
	  int count = 0;
	  while (CORBA::is_nil (this->_scheduler.in ())){
	    if (count >= QMS_DEFAULT_number_of_retries){
	      ACE_ERROR ((LM_ERROR,"(%P|%t) Unable to get the scheduler.\n"));
	      ACE_TRY_THROW (CORBA::BAD_PARAM ());
	    }
	    ACE_OS::sleep (sleep_time);
	    DEBUG0 (6, "retrying getting scheduler\n");
	    CORBA::Object_var sched_obj=
	      this->_naming_context->resolve (schedule_name, ACE_TRY_ENV);
	    ACE_TRY_CHECK;

	    this->_scheduler =
	      RtecScheduler::Scheduler::_narrow(sched_obj.in (), ACE_TRY_ENV);
	    ACE_TRY_CHECK;
	    DEBUG0 (6, "Narrowed  the scheduler handle\n");
	    count++;
	  }
	}
	else {
	  DEBUG0 (6, "Got the scheduler\n");
	}
      }
      else
       {
	 DEBUG0 (6, "Already Had scheduler\n");
       }
    }

  ACE_CATCH (CosNaming::NamingContext::AlreadyBound, ex)
    {
      ACE_PRINT_EXCEPTION (ex, "name service already bound :");
      this->disconnect();
      ACE_RE_THROW;
    }
Exemplo n.º 10
0
 ACE_CATCH (CORBA::SystemException, sysex)
   {
     ACE_PRINT_EXCEPTION (sysex, "System Exception :");
     this->disconnect();
     ACE_RE_THROW;
   }
Exemplo n.º 11
0
/**
 *  @param argc Number of command line arguments
 *  @param argv Array of command line arguments
 * Usage:   [CORBA OPTIONS] [OPTIONS]
 *     -  -h             : This help text
 *     -  -v             : Prints out the version
 *     -  -file Filename : Read XML data from here
 *     -  -f    Filename : Read XML data from here
 *     -  -ecname NAME   : The name of the event channel
 *     -  -e      NAME   : The name of the event channel
 */
int
main (int argc, char *argv[])
{
  QMS_Trace ("main", __LINE__, __FILE__);
  DEBUG0 (DEBUG_L_ENTER, "DEBUG: starting\n");
  signal(SIGTERM,sig_handler);
  signal(SIGINT,sig_handler);
  signal(SIGABRT,sig_handler);
  signal(SIGHUP,sig_handler);

  DEBUG0 (DEBUG_L_CALL, "DEBUG: added signal handling\n");
  ACE_OS::srand(time(0));

  DEBUG3 (DEBUG_L_CALL, "DEBUG: starting the API With ID = %d"
	  " Send event type = %d Recieve event type = %d\n" ,
	  Query_Supplier, QMS_Remos_Query, QMS_Remos_Data);

  char * ecname_p = (char *) "QMS_Channel";

  DEBUG0 (DEBUG_L_CALL, "DEBUG: parsing arguments\n");
  for (int i = 0; i < argc; i++)
   {
     if (!argv[i])           { break; }
     if (argv[i][0] != '-')  { continue; }
     int j = 1;
     if (argv[i][1] == '-')  {
       if (argv[i][2] == 0)  { break; }	// handle -- end of options
       j = 2;			// handle --argument
     }
     if (strstr((argv[i] + j), "ORB"))  { continue; }
     if (! strcmp((argv[i] + j), "help") || strchr((argv[i] + j), 'h'))
      {				// -h or --help
	cout << argv[0] << version << endl
	     << "Usage: " << argv[0] << "[CORBA OPTIONS] [OPTIONS]"
	     << endl
	     << "\t-h             : This help text"  << endl
	     << "\t-v             : Prints out the version"  << endl
	     << "\t-file Filename : Read XML data from here"  << endl
	     << "\t-f    Filename : Read XML data from here"  << endl
	     << "\t-ecname NAME   : The name of the event channel"  << endl
	     << "\t-e      NAME   : The name of the event channel"  << endl
	  ;
	exit (0);
      }
     if (! strcmp((argv[i] + j), "version") || strchr((argv[i] + j), 'v'))
      {
	cout << argv[0] << ": Version "<< version << endl;
	exit (0);
      }

     if (! strcmp((argv[i] + j), "file") || strchr((argv[i] + j), 'f'))
      {
	filename_p = (char *) malloc (sizeof(argv[i + 1]) + 1);
	strcpy(filename_p,argv[i + 1]);
	continue;
      }
     if (! strcmp((argv[i] + j), "ecname") || strchr((argv[i] + j), 'f'))
      {
	ecname_p = (char *) malloc (sizeof(argv[i + 1]) + 1);
	strcpy(ecname_p,argv[i + 1]);
	continue;
      }
     DEBUG1 (DEBUG_L_ERROR, "unknown argument %s", argv[i] );
   }


  ACE_DECLARE_NEW_CORBA_ENV;
  ACE_TRY
    {

      qms_api.init(argc, argv,
		   Query_Supplier,  // My ID
		   QMS_Remos_Query, //  The data I send
		   QMS_Remos_Data,  // The data I get
		   ecname_p
		   );
      ACE_TRY_CHECK;


      qms_api.register_callback(my_cb_func, 0);
      ACE_TRY_CHECK;
      qms_api.connect_supplier();
      ACE_TRY_CHECK;
      qms_api.connect_consumer();
      ACE_TRY_CHECK;

      DEBUG0 (DEBUG_L_CALL, "DEBUG: Spawning a thread\n");

      if (ACE_Thread::spawn((ACE_THR_FUNC)generate_query,
			    0,	// arg
			    THR_JOINABLE, // flags
			    0,	// t_id
			    0,	// t_handle
			    ACE_DEFAULT_THREAD_PRIORITY,
			    0,	// stack
			    0,	// stack_size
			    0	// thread_adapter
			    )==-1)
       {
	 DEBUG0 (DEBUG_L_ERROR, "DEBUG: Error in spawning thread\n");
       }
      DEBUG0 (DEBUG_L_CALL, "DEBUG: Entering Loop\n");
      qms_api.listen();
      ACE_TRY_CHECK;
    }
  ACE_CATCH (CORBA::SystemException, sysex)
    {
      ACE_PRINT_EXCEPTION (sysex, "System Exception :");
      qms_api.connect_supplier();
      qms_api.connect_consumer();
	exit (1);
    }
        /**
         * Receiver::handle_event()
         *
         *   Description:
         *     Processes an event that arrived through the MC-Channel
         *
         *   Parameters:
         *     _eventData: header of IP/MC Event packet
         *     _iov:       Complete packet
         */
        int Receiver::handle_event(EventData &_eventData, iovec *_iov) {
            ACE_INET_Addr from;

            /* Drop the packet if data doesn't fit */
            if ((_eventData.requestSize    <  _eventData.fragmentSize) ||
                (_eventData.fragmentOffset >= _eventData.requestSize)  ||
                (_eventData.fragmentId     >= _eventData.fragmentCount)) {

                PRINT_DBG(DBG_INFO, "Dropping packet");

                return 0;
            }
            /* Index the incomplete (due to fragmentation) requests */
            RequestIndex     mapIndex(from, _eventData.requestId);
            RequestMapEntry *entry;

            if (this->requestMap_.find(mapIndex, entry) == -1) {

                /* Create an entry and insert it... */
                RequestEntry *requestEntry = new RequestEntry(_eventData.byteOrder,
                                                              _eventData.requestId,
                                                              _eventData.requestSize,
                                                              _eventData.fragmentCount);

                /* Drop the packet if impossible to bind entry to map */
                if ((requestEntry == 0) || (this->requestMap_.bind(mapIndex, requestEntry, entry) == -1)) {
                    PRINT_DBG(DBG_VERBOSE, "Unable to index, dropping");

                    return 0;
                }
            }
            /* Validate the message... */
            if (entry->int_id_->validateFragment(_eventData.byteOrder,
                                                 _eventData.requestSize,
                                                 _eventData.fragmentSize,
                                                 _eventData.fragmentOffset,
                                                 _eventData.fragmentId,
                                                 _eventData.fragmentCount) == 0) {
                PRINT_DBG(DBG_VERBOSE, "Fragment rejected");

                return 0;
            }
            /* Already received this fragment */
            if (entry->int_id_->testReceived(_eventData.fragmentId) == 1) {
                PRINT_DBG(DBG_VERBOSE, "Duplicate Fragment, dropping");

                return 0;
            }
            /* Copy the payload into the fragment buffer */
            char *buffer = (char *)_iov[0].iov_base + HEADER_SIZE;
            int   bufferLen = _iov[0].iov_len - HEADER_SIZE;
            memcpy(entry->int_id_->fragmentBuffer(_eventData.fragmentOffset),
                   buffer,
                   bufferLen);
            /* Mark datagram fragment as received */
            entry->int_id_->markReceived(_eventData.fragmentId);
            /* If the message is not complete we must return... */
            if (!entry->int_id_->complete())
                return 0;
            /* Demarshal datagram payload */
            ACE_DECLARE_NEW_CORBA_ENV;
            ACE_TRY {
                CosNotification::StructuredEvent event;

                /* Decode datagram */
                entry->int_id_->decode(event ACE_ENV_ARG_PARAMETER);
                ACE_TRY_CHECK;

                /* Drop packet if it's too old */
                if (ACE_OS::gettimeofday().msec() - _eventData.timestamp > configuration_->getEventMaxAge()) {
                    PRINT_DBG(DBG_VERBOSE, "Packet " << _eventData.requestId << " dropped because it was too old");
                    return 0;
                }

                /* Send event to event channel */
                sendEvent(event ACE_ENV_ARG_PARAMETER);
                ACE_TRY_CHECK;

            } ACE_CATCHANY {
                ACE_PRINT_EXCEPTION(ACE_ANY_EXCEPTION, "NotifyMulticastReceiver::handle_input");
            }
            ACE_ENDTRY;

            return 0;
        }
Exemplo n.º 13
0
int main(int argc, char* argv[]) 
{

    if (argc<2)
    {
      ACE_OS::printf ("usage: %s <object_name>\n", argv[0]);
      return -1;
    }
    
    
    try
	{
	ACE_CString g_strCmdLn;
	for (int i=argc-1; i>=0; i--)
	    g_strCmdLn = ACE_CString(argv[i])+ " " + g_strCmdLn;

	if (g_strCmdLn.find("-ORBDottedDecimalAddresses")==ACE_CString::npos)
	    g_strCmdLn += " -ORBDottedDecimalAddresses 1";

	ACE_TCHAR **m_argv = argv;
	int m_argc = argc;
	ACE_OS::string_to_argv((ACE_TCHAR*)g_strCmdLn.c_str(),
			 m_argc,
			 m_argv);
	BACI_CORBA::InitCORBA(m_argc, m_argv);

	LoggingProxy EP_log (0, 0, 31, 0);
	LoggingProxy::init (&EP_log);

	/**
	 * Get reference to a device
	 */

	char fileName[64];
	sprintf(fileName, "file://%s.ior", argv[1]);
	CORBA::Object_var object = BACI_CORBA::getORB()->string_to_object (fileName);
	

	if (CORBA::is_nil(object.in())) 
	    {
	    ACE_DEBUG ((LM_DEBUG, "Cannot get Object"));
	    return -1;
	    }

	// Try to narrow the object reference to a PowerSupply reference.
	ENUMPROP_TEST::enumpropTestDevice_var dev = ENUMPROP_TEST::enumpropTestDevice::_narrow (object.in ());
	
	if (CORBA::is_nil(dev.in())) 
	    {
	    ACS_SHORT_LOG((LM_DEBUG, "Failed to narrow enumnTestDevice "));
	    return 0;
	    }
	ACS_SHORT_LOG((LM_DEBUG, "Device narrowed."));

	// Get current stat
	ENUMPROP_TEST::ROStates_var currentState = dev->currentState();
	

	//   get states description	
	ACS::stringSeq_var description = currentState->statesDescription( );
	

	AlarmCBpattern alarmCB (currentState.in());
        ACS::Alarmpattern_var alarmCBObj = alarmCB._this();

        ACS::CBDescIn desc;
	desc.id_tag = 1;

	ACS::Subscription_var monitor = currentState->new_subscription_AlarmEnum(alarmCBObj.in(), desc);
	//	monitor->set_timer_trigger(10000000);

	ACS_SHORT_LOG((LM_DEBUG, "(main thread) Going in main loop sleep..."));
	ACE_Time_Value tv(5);
	BACI_CORBA::getORB()->run(tv);

	ACS_SHORT_LOG((LM_DEBUG, "(main thread) Exit ... "));
	monitor->destroy();

        /* Allow time for the done() callback to come back */
	BACI_CORBA::getORB()->run(tv);

	BACI_CORBA::DoneCORBA();
	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex,"Error!");
	return -1;
	}
    ACE_CHECK_RETURN (-1);


    return 0;
}
int
main (int argc, char *argv[])
{
  try
  {
    // Initialize orb
    CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "");

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

    CORBA::Object_var obj = orb->string_to_object (bdc_ior);

    CUTS::Benchmark_Data_Collector_var comp = CUTS::Benchmark_Data_Collector::_narrow (obj.in());
    if (CORBA::is_nil (comp.in ()))
    {
      ACE_ERROR_RETURN ((LM_ERROR, "Unable to acquire Benchmark_Data_Collector objref\n"), -1);
    }

    CUTS::BDC_Control_Handle_var controls = comp->provide_controls();
    if (CORBA::is_nil (controls.in()))
    {
      ACE_ERROR_RETURN ((LM_ERROR, "Unable to acquire controls objref\n"), -1);
    }

    CUTS::Path_Measurement_var online_measurements = comp->provide_online_measurements();
    if (CORBA::is_nil (online_measurements.in()))
    {
      ACE_ERROR_RETURN ((LM_ERROR, "Unable to acquire online_measurements objref\n"), -1);
    }

    CUTS_x002eBenchmark_USCOREData_USCORECollector service (controls.in(), online_measurements.in());

    int m, s;
     // master and slave sockets

    m = soap_bind(&service, "localhost", port, 100);

    if (m < 0)
      soap_print_fault(&service, stderr);

    else
    {
      fprintf(stderr, "Listening for SOAP requests on port = %d\n", port);

      for (int i = 1; ; i++)
      {
        s = soap_accept(&service);
        if (s < 0)
        {
          soap_print_fault(&service, stderr);
          break;
        }

        fprintf(stderr, "%d: Accepted connection from IP=%d.%d.%d.%d socket=%d\n", i,
                (service.ip >> 24)&0xFF,
                (service.ip >> 16)&0xFF,
                (service.ip >> 8)&0xFF,
                service.ip&0xFF, s);

        if (service.serve() != SOAP_OK) // process RPC request
        soap_print_fault(&service, stderr);
         // print error
        fprintf(stderr, "SOAP Request served\n");

        soap_destroy(&service);
         // clean up class instances
        soap_end(&service);
         // clean up everything and close socket
      }
    }
  }

  catch (CORBA::Exception& ex)
  {
    ACE_PRINT_EXCEPTION (ex, "CORBA::Exception\n");

    ACE_ERROR_RETURN ((LM_ERROR, "Uncaught CORBA exception\n"), 1);
  }

  return 0;
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{

  if (argc<4){
    ACE_OS::printf ("usage: testClient <server_name> <depth> <isError> [iteration]\n");
    return -1;
  }//if

  

// create logging proxy
  LoggingProxy m_logger (0, 0, 31, 0);
  LoggingProxy::init (&m_logger); 

  CORBA::ORB_var orb;
  ACS_TEST_INIT_CORBA;

  // init ACS error system
  ACSError::init (orb.ptr());


  /**************************************/
  acserrOldTest_var test;
  int depth;
  sscanf (argv[2], "%d", &depth);
  bool isErr = *argv[3]-'0';
  int iteration=1, i=1;
  const int size = 20;  // max value 1.84 x 10^19
  char printBuf[size+1];

  if (argc>4)
	sscanf (argv[4], "%d", &iteration); 
  
  ACS_DEBUG("main", "****** Test Block *****");
 
  try
    {
      ACS_DEBUG("acserrOldTestClient", "Getting object reference ... ");
      char fileName[64];
      sprintf(fileName, "file://%s.ior", argv[1]);
      CORBA::Object_var testObj = orb->string_to_object (fileName);

      ACS_DEBUG("acserrOldTestClient", "Narrowing it .... ");
      test = acserrOldTest::_narrow (testObj.in());

      unsigned long long numToPrint; 
      while( iteration >= i ){
	ACS_SHORT_LOG((LM_INFO, "Performing test1 (remote call)... (%d/%d)", i, iteration));
	ACSErr::ErrorTrace *c = test->test (depth, isErr);
	
	ACSError error(c, true);
	ACS_SHORT_LOG((LM_INFO, "Stack depth: %d", error.getDepth()));
	error.log();

	//ACSError *error = new ACSError (c, true) -> new ACS_ERROR (c, true);
	while (c!=NULL){
	  ACS_SHORT_LOG((LM_INFO, "FileName:   \"%s\"",error.getFileName()));
	  ACS_SHORT_LOG((LM_INFO, "LineNumber: \"%d\"",error.getLineNumber()));  
	  ACS_SHORT_LOG((LM_INFO, "Routine:    \"%s\"",error.getRoutine()));
          ACS_SHORT_LOG((LM_INFO, "HostName:   \"%s\"",error.getHostName()));
	  ACS_SHORT_LOG((LM_INFO, "Process:    \"%s\"",error.getProcess()));
          ACS_SHORT_LOG((LM_INFO, "Thread:     \"%s\"",error.getThread()));
          for (int ii = 0; ii < size; ii++) printBuf[ii] = ' ';
          printBuf[size] = '\0';
          numToPrint = error.getTimeStamp(); 
          for (int ii = size - 1; ii >= 0; ii--) {
                 printBuf[ii] = numToPrint % 10 + '0';
                 numToPrint /= 10;
                 if (numToPrint == 0)
                  break;
             }
	  ACS_SHORT_LOG((LM_INFO, "TimeStamp:  \"%s\"",printBuf));
	  ACS_SHORT_LOG((LM_INFO, "ErrorType:  \"%d\"",error.getErrorType()));
	  ACS_SHORT_LOG((LM_INFO, "ErrorCode:  \"%d\"",error.getErrorCode()));
	  ACS_SHORT_LOG((LM_INFO, "Severity:   \"%d\"", error.getSeverity()));
          ACS_SHORT_LOG((LM_INFO, "Description: \"%s\"",error.getDescription()));
	  c = error.getNext();
	  }	
	i++;
      }//while
      
   
    }
  catch( CORBA::Exception &ex)
    {    
      ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
      return -1;
    }
  ACS_SHORT_LOG((LM_INFO, "Test1 performed."));

//test2
  i=1;
  while (i<=iteration){
    try
      {
	ACS_SHORT_LOG((LM_INFO, 
              "Performing test2 (remote call - exceptions) ... (%d/%d)", i, iteration));
	test->testExceptions (depth, isErr);
      }
    catch (ACSErr::ACSException &ex)
      {
	ACS_SHORT_LOG((LM_INFO, "Catch ACSException !"));
	ACSError exception (ex); // put CORBA exception (ACSException) into ACSError wrapper
	exception.log();
      }
    catch( CORBA::Exception &_ex)
      {    
	ACE_PRINT_EXCEPTION (_ex, "EXCEPTION CAUGHT");
	return -1;
      }
    
    i++;
  }//while

  ACS_SHORT_LOG((LM_INFO, "Test2 performed."));

// test3 (no error)
  i=1;
  while (i<=iteration){
    try
      {
	ACS_SHORT_LOG((LM_INFO, 
              "Performing test3 (no error) ... (%d/%d)", i, iteration));
	test->testNoError ();
      }
    catch( CORBA::Exception &_ex)
      {    
	ACE_PRINT_EXCEPTION (_ex, "EXCEPTION CAUGHT");
	return -1;
      }
    
    i++;
  }//while

  ACS_SHORT_LOG((LM_INFO, "Test3 performed."));

  test->shutdown();
  ACE_OS::sleep(5);
  LoggingProxy::done();

  return 0;
}
Exemplo n.º 16
0
  ACE_CATCH (CORBA::UserException, userex)
    {
      ACE_PRINT_EXCEPTION (userex,
			   "User Exception getting QMS_Trader_ECInfo:");
      ACE_RE_THROW;
    }
Exemplo n.º 17
0
  ACE_CATCH (CORBA::SystemException, sysex)
    {
      ACE_PRINT_EXCEPTION (sysex, 
			   "System Exception getting QMS_Trader_ECInfo:");
      ACE_RE_THROW;
    }
Exemplo n.º 18
0
/**
 * @brief Get a reference to the QMS Trader ECInfo component
 * @param ACE_TRY_ENV CORBA env for propogating exceptions
 *
 * First, if we already have a handle on the QMS Trader component, we
 * return immediately. If not, we query the CORBA Trading service for
 * the YP offer of the EC Info component, narrow it down, and stash
 * the object reference away.
 */
void
Test_Client::get_ec_registry(CORBA::Environment &ACE_TRY_ENV)
{
  QMS_Trace("Test_Client::get_ec_registry", __LINE__, __FILE__);
  DEBUG0(DEBUG_L_ENTER, "DEBUG: Test_Client::get_ec_registry\n");
  if(!CORBA::is_nil(this->_ec_registry.in()))
   {
     return;
   } /* end of if(!CORBA::is_nil(this->_ec_registry)) */
  
  ACE_TRY
    {
      CosTrading::Lookup_var lookup_var =
	this->_handles.get_lookup_handle(ACE_TRY_ENV);
      ACE_TRY_CHECK;

      CosTrading::Lookup_ptr lookup_p = lookup_var.in();
      assert(lookup_p);
      assert(!CORBA::is_nil(lookup_p));

      // Perparing to do an import operation.  Should some of these go
      // into the sensor object itself?
      PolicySeq policies;	             //empty sequence

      CosTrading::Lookup::SpecifiedProps desired_props;  // No properties
      desired_props._d(Lookup::all);         // Return all properties

      CosTrading::PolicyNameSeq_var policies_applied;      // out param
      CosTrading::OfferSeq *offer_seq_ptr = 0; // out param
      CosTrading::OfferSeq_out offer_seq_out (offer_seq_ptr);
      CosTrading::OfferIterator_var iterator;              // out param

      // We ask for a single result to be returned, since we
      // essentially want the first ec registry object. This
      // simplifies the code; however, if  needed, we can go through
      // and iterate over all offers.
      lookup_p->query("STDC_QMS_CITIZEN_QMS_TRADER",    // IN string
		      "QMS_UNIQ_NAME_CATEGORY == 'QMS_TRADER' ",// IN contraint
		      "",                             // IN preferences
		      policies,                       // IN policies
		      desired_props,                  // IN desired properties
		      1,                              // IN how many
		      offer_seq_out,                  // OUT Offers
		      iterator,                       // OUT Iterator
		      policies_applied                // OUT policies applied
		      );
      ACE_TRY_CHECK;

      // Processing the results
      if(offer_seq_out->length() == 0)
       {
	 cerr << "No Trader Offers found" << endl;
	 ACE_TRY_THROW (CORBA::BAD_PARAM ());
       } /* end of if(offer_seq_out->length() == 0) */
      else
       {
	 // Extract asn object reference
	 const CosTrading::OfferSeq& offer_seq = *offer_seq_ptr;
	 this->_ec_registry = 
	   STDC::QMS::Citizen::QMS_Trader_ECInfo::_narrow(offer_seq[0].reference);
	 if(CORBA::is_nil(this->_ec_registry.in()))
	  {
	    cerr << "Service provider is not an ec registry" << endl;
	    ACE_TRY_THROW (CORBA::BAD_PARAM());
	  } /* end of if(CORBA::is_nil(this->_ec_registry)) */
       } /* end of else */
      if (!CORBA::is_nil(iterator.in()))
       {
	 iterator->destroy();
	 ACE_TRY_CHECK;
       }
    }
  ACE_CATCH (CosTrading::IllegalConstraint, constex)
    {
      ACE_PRINT_EXCEPTION (constex, 
			   "Illegal Constraint getting QMS_Trader_ECInfo:");
      if (constex.constr.in () != 0)
        ACE_DEBUG ((LM_DEBUG, "Invalid name: %s\n", constex.constr.in ()));
      ACE_RE_THROW;
    }
Exemplo n.º 19
0
int main(int argc, char* argv[]) 
{

    
    
    try
	{
	ACE_CString g_strCmdLn;
	for (int i=argc-1; i>=0; i--)
	    g_strCmdLn = ACE_CString(argv[i])+ " " + g_strCmdLn;

	if (g_strCmdLn.find("-ORBDottedDecimalAddresses")==ACE_CString::npos)
	    g_strCmdLn += " -ORBDottedDecimalAddresses 1";

	ACE_TCHAR **m_argv = argv;
	int m_argc = argc;
	ACE_OS::string_to_argv((ACE_TCHAR*)g_strCmdLn.c_str(),
			 m_argc,
			 m_argv);
	BACI_CORBA::InitCORBA(m_argc, m_argv);
	/**
	 * Get reference to a device
	 */

	char fileName[64];
	sprintf(fileName, "file://%s.ior", argv[1]);
	CORBA::Object_var object = BACI_CORBA::getORB()->string_to_object (fileName);
	
	
	if (CORBA::is_nil(object.in())) 
	    {
	    ACE_DEBUG ((LM_DEBUG, "Cannot get Object"));
	    return -1;
	    }

	// Try to narrow the object reference to a PowerSupply reference.
	ENUMPROP_TEST::enumpropTestDevice_var dev = ENUMPROP_TEST::enumpropTestDevice::_narrow (object.in ());
	
	if (CORBA::is_nil(dev.in())) 
	    {
	    ACS_SHORT_LOG((LM_DEBUG, "Failed to narrow enumnTestDevice "));
	    return 0;
	    }
	ACS_SHORT_LOG((LM_DEBUG, "Device narrowed."));

	// Get current stat
	ENUMPROP_TEST::ROStates_var currentState = dev->currentState();
	
	
	//   get states description	
	ACS::stringSeq_var description = currentState->statesDescription( );
	
        
	TestCBpattern cbStates (currentState.in());
        ACS::CBpattern_var cbStatesObj = cbStates._this();

        ACS::CBDescIn desc;
	desc.id_tag = 1;
	ACS::Monitor_var monitor = currentState->create_monitor(cbStatesObj.in(), desc);
	monitor->set_timer_trigger(10000000);
	/**
	 * Enter main loop and stays there for a 
	 * fixed amount of time
	 */
	ACS_SHORT_LOG((LM_DEBUG, "(BACIClient main thread) Going in main loop sleep..."));
 
	BACI_CORBA::getORB()->run();

	BACI_CORBA::DoneCORBA();

	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex,"Error!");
	return -1;
	}
    
    return 0;
}
Exemplo n.º 20
0
int
main (int argc, char *argv[])
{
  // Try to set real-time scheduling class. Requires login as
  // superuser or administrator.
  //set_rt ();
  
  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.
      status = parse_args (argc, argv);
      
      if (0 != status)
        {
          return status;
        }

      ::DDS::DomainParticipant_var dp = 
        dpf->create_participant (TEST_DOMAIN, 
                                 PARTICIPANT_QOS_DEFAULT, 
                                 ::DDS::DomainParticipantListener::_nil ());

      if (CORBA::is_nil (dp.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%P|%t ERROR: create_participant ")
                             ACE_TEXT ("failed.\n")),
                            1);
        }

      DDS::ReturnCode_t ret_code = ::DDS::RETCODE_OK;

      BytesTypeSupportImpl* bytes_ts_servant =
        new BytesTypeSupportImpl ();
        
      PortableServer::ServantBase_var safe_servant =
        bytes_ts_servant;

      BytesTypeSupport_var bytes_ts = 
        TAO::DCPS::servant_to_reference_2<BytesTypeSupport> (
          bytes_ts_servant);
      
      ret_code = bytes_ts->register_type (dp.in (), TEST_TYPE);

      if (::DDS::RETCODE_OK != ret_code)
        {
          ACE_ERROR_RETURN ((LM_ERROR, 
                             ACE_TEXT ("%P|%t ERROR: Failed to register ")
                             ACE_TEXT ("type support.")
                             ACE_TEXT ("for data size %d\n"),
                             DATA_SIZE),
                            1);
        }

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

      topic_qos.resource_limits.max_samples_per_instance =
        MAX_SAMPLES_PER_INSTANCE;
      topic_qos.resource_limits.max_instances = MAX_INSTANCES;
      topic_qos.resource_limits.max_samples = MAX_SAMPLES;

      if (isReliable)
        {
      
          topic_qos.reliability.kind = ::DDS::RELIABLE_RELIABILITY_QOS;
          topic_qos.reliability.max_blocking_time.sec = max_mili_sec_blocking / 1000;
      
          topic_qos.reliability.max_blocking_time.nanosec = 
            (max_mili_sec_blocking % 1000) * 1000*1000;
        }
      else
        {
          topic_qos.reliability.kind = ::DDS::BEST_EFFORT_RELIABILITY_QOS;          
        }

      if (QoS_KEEP_ALL)
        {
          topic_qos.history.kind = ::DDS::KEEP_ALL_HISTORY_QOS;
        }

      ::DDS::Topic_var topic = 
      dp->create_topic (test_topic_name.c_str (), 
                            TEST_TYPE, 
                            topic_qos, 
                            ::DDS::TopicListener::_nil ());

      ACE_DEBUG ((LM_DEBUG, "(%P|%t)The current topic is %s\n",
         test_topic_name.c_str()));
     
      if (CORBA::is_nil (topic.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%P|%t ERROR: ")
                             ACE_TEXT ("create_topic failed.\n")),
                            1);
        }

      // Create the publisher
      ::DDS::Publisher_var pub =
        dp->create_publisher (PUBLISHER_QOS_DEFAULT,
                              ::DDS::PublisherListener::_nil ());
      
      if (CORBA::is_nil (pub.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%P|%t ERROR: ")
                             ACE_TEXT ("create_publisher failed.\n")),
                            1);
        }

      // Initialize the transport
      if (0 != ::init_writer_tranport ())
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("%P|%t ERROR: ")
                           ACE_TEXT ("init_transport failed!\n")),
                          1);
      }

      // Attach the publisher to the transport.
      ::TAO::DCPS::PublisherImpl* pub_impl =
        ::TAO::DCPS::reference_to_servant< ::TAO::DCPS::PublisherImpl,
                                           ::DDS::Publisher_ptr> (
          pub.in ());

      if (0 == pub_impl)
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%P|%t ERROR: Failed ")
                             ACE_TEXT ("to obtain servant ")
                             ACE_TEXT ("::TAO::DCPS::PublisherImpl\n")),
                            1);
        }

      TAO::DCPS::AttachStatus attach_status =
        pub_impl->attach_transport (writer_transport_impl.in ());

      if (attach_status != TAO::DCPS::ATTACH_OK)
        {
          // We failed to attach to the transport for some reason.
          std::string status_str;

          switch (attach_status)
            {
              case TAO::DCPS::ATTACH_BAD_TRANSPORT:
                status_str = "ATTACH_BAD_TRANSPORT";
                break;
              case TAO::DCPS::ATTACH_ERROR:
                status_str = "ATTACH_ERROR";
                break;
              case TAO::DCPS::ATTACH_INCOMPATIBLE_QOS:
                status_str = "ATTACH_INCOMPATIBLE_QOS";
                break;
              default:
                status_str = "Unknown Status";
                break;
            }

          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%P|%t ERROR: Failed to ")
                             ACE_TEXT ("attach to the transport. ")
                             ACE_TEXT ("AttachStatus == %s\n"),
                             status_str.c_str()),
                            1);
        }

      // Create the datawriters
      ::DDS::DataWriterQos dw_qos;
      pub->get_default_datawriter_qos (dw_qos);
      pub->copy_from_topic_qos (dw_qos, topic_qos);

      ::DDS::DataWriter_var * dws =
        new ::DDS::DataWriter_var[num_datawriters];

      // Create one or multiple datawriters belonging to the same 
      // publisher.
      for (int k = 0; k < num_datawriters; ++k)
        {
          dws[k] = pub->create_datawriter (topic.in () ,
                                          dw_qos,
                                          ::DDS::DataWriterListener::_nil ());

          if (CORBA::is_nil (dws[k].in ()))
            {
              ACE_ERROR_RETURN ((LM_ERROR,
                                ACE_TEXT ("%P|%t ERROR: ")
                                ACE_TEXT ("create_datawriter failed.\n")),
                                1);
            }
        }

      Writer** writers = new Writer* [num_datawriters] ;

      // If we're using UDP then oversend the number of samples
      if (usingUdp)
      {
        // Using the precedence here from NDDS publisher for determining
        // oversampling value.
        STATS_SAMPLES = (STATS_SAMPLES + PRIMER_SAMPLES) * OVERSAMPLEMULTIPLIER;
      }

      for (int p = 0; p < num_datawriters; ++p)
        {
          writers[p] = new Writer (dws[p].in (),
                                   pub_output_file.c_str (),
                                   PRIMER_SAMPLES,
                                   STATS_SAMPLES,
                                   DATA_SIZE,
                                   num_datareaders,
                                   id + p); 
          writers[p]->start ();
        }


      bool writers_finished = false;

      while (!writers_finished)
        {
          ACE_Guard<ACE_Recursive_Thread_Mutex> just_me (done_lock_);
          
          // wait for a writer to signal so we done spin
          // waiting to see if the publisher is done.
          done_condition_.wait ();
          writers_finished = true;
          
          for (int m = 0; m < num_datawriters; ++m)
            {
              writers_finished =
                writers_finished && writers[m]->is_finished ();
            }
        }
        
      ACE_OS::sleep (1);
        
      // Clean up publisher objects
      pub->delete_contained_entities ();

      delete [] dws;

      for (int q = 0; q < num_datawriters; ++q)
        {
          delete writers[q];
        }

      delete [] writers;

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

      ACE_OS::sleep (2);
      TheTransportFactory->release ();

      TheServiceParticipant->shutdown (); 

      writer_transport_impl = 0;
    }
  catch (CORBA::Exception &ex)
    {
      ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION,
                           "Exception caught in main.cpp:");
      return 1;
    }

  return status;
}
Exemplo n.º 21
0
int acslogErrorServer (char *szCmdLn){
  int  argc;
  char *argv[100];

  argc = argUnpack(szCmdLn, argv);
  argv[0] = " acslogErrorServer";
#else
  int acslogErrorServer (int argc, char *argv[]){
#endif // defined( MAKE_VXWORKS )

  CORBA::ORB_var orb;
  

  if (argc<2){
    ACE_OS::printf ("usage: acslogErrorServer <server_name> [destination_server_name] \n");
    return -1;
  }
  
  try
    {
      // Initialize the ORB
      ACS_DEBUG(" acslogErrorServer", "Initialising ORB ... ");
      orb = CORBA::ORB_init (argc, argv, 0);
      ACS_DEBUG ("acslogErrorServer", "ORB initialsed !");
    }
  catch( CORBA::Exception &ex )
    {
      ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB");
      return -1;
    }

  // create logging proxy
  ACS_DEBUG (" acslogErrorServer", "Creating logging proxy ... ");
  LoggingProxy *m_logger = new LoggingProxy(0, 0, 31, 0);
  LoggingProxy::init (m_logger);  
  ACS_DEBUG (" acslogErrorServer", "Logging proxy successfully created !");

  try
    {

      //Naming Service 
      ACS_DEBUG (" acslogErrorServer", "Resolving  Naming service ... ");
      ACE_CString nameService;
      nameService +="corbaloc::";
      nameService += ACSPorts::getIP();
      nameService += ":"; 
      nameService += ACSPorts::getNamingServicePort().c_str();
      nameService += "/"; 
      nameService += acscommon::NAMING_SERVICE_NAME;

      CORBA::Object_var naming_obj = orb->string_to_object(nameService.c_str());
      if (!CORBA::is_nil (naming_obj.in ()))
	{
	  CosNaming::NamingContext_var naming_context =
	    CosNaming::NamingContext::_narrow (naming_obj.in ());
	  ACS_DEBUG ("acslogErrorServer", "Naming Service resolved !");

	  CosNaming::Name name;
	  name.length(1);
	  name[0].id = CORBA::string_dup("Log");
	  CORBA::Object_var log_obj = naming_context->resolve(name);

	  if (!CORBA::is_nil (log_obj.in()))
	    {
	      Logging::AcsLogService_var logger = Logging::AcsLogService::_narrow(log_obj.in());
	      ACS_DEBUG ("acslogErrorServer", "Logging Service resolved !");

	      m_logger->setCentralizedLogger(logger.in());
	    }
	  else
	    {
	      ACS_DEBUG ("acslogErrorServer", "Failed to initialise the Logging Service!");
	    }

	}
      else
	{
	  ACS_DEBUG ("acslogErrorServer", "Failed to initialise the NameService!");
	}//if-else
    }
  catch( CORBA::Exception &ex )
    {
      ACE_PRINT_EXCEPTION(ex, "Failed to get and set the centralized logger");
    }

  try
    {
      //Get a reference to the RootPOA
      CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
      
      PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
      
   
      PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
      
      /* 
      CORBA::PolicyList policy_list;
      policy_list.length(5);
      policy_list[0] = root_poa->create_request_processing_policy (PortableServer::USE_DEFAULT_SERVANT);
     policy_list[1] =  root_poa->create_id_uniqueness_policy (PortableServer::MULTIPLE_ID);
      policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); 
      policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); 
      policy_list[4] =  root_poa->create_lifespan_policy (PortableServer::PERSISTENT);
      printf("policies are created !\n");

      PortableServer::POA_var poa = root_poa->create_POA("cdbSrv", poa_manager.in(), policy_list);
      printf("Poa created !\n");

      for (CORBA::ULong i = 0; i < policy_list.length (); ++i) {
	CORBA::Policy_ptr policy = policy_list[i];
	policy->destroy ();
      }
      printf("Policies are destructed !\n");
      */


#ifdef MAKE_VXWORKS      
      ACSError::processName (szCmdLn);
#else 
      char *buf;
      ACE_OS::argv_to_string (argv, buf);
      ACSError::processName (buf);
      delete[] buf;
#endif      
      ACS_DEBUG ("acslogErrorServer", "Creating test object ...");
      ESTest_var dest;
      
      if (argc>2){
	ACS_DEBUG ("acslogErrorServer", "Getting object reference ... ");
	char refName[64];
	sprintf(refName, "file://%s.ior", argv[2]);
	CORBA::Object_var destObj = orb->string_to_object (refName);
	

	ACS_DEBUG ("acslogErrorServer", "Narrowing it .... ");
	dest = ESTest::_narrow (destObj.in());
      }//if

      ESTestImpl  esTest (dest.in(), argv[1]);
      ESTest_var testObj = esTest._this ();
      
           
      poa_manager->activate ();
      
      ACS_DEBUG ("acslogErrorServer","POA Manager -> activate");
      
      ACS_DEBUG_PARAM ("acslogErrorServer", "Writing ior to the file: %s .... ", argv[1]);
      char* ior =  orb->object_to_string (testObj.in());
      
      
      char fileName[64];
      sprintf(fileName, "%s.ior", argv[1]);
      FILE *output_file = ACE_OS::fopen (fileName, "w");
      if (output_file == 0) {
	ACS_SHORT_LOG ((LM_ERROR,
			   "Cannot open output files for writing IOR: ior.ior"));
	return  -1;
      }

      int result = ACE_OS::fprintf (output_file, "%s", ior);
      if (result < 0) {
	ACS_SHORT_LOG ((LM_ERROR,
			   "ACE_OS::fprintf failed while writing %s to ior.ior\n", ior));
	return  -1;
      }

      ACE_OS::fclose (output_file);
      
      ACS_DEBUG ("acslogErrorServer", "Waiting for requests ...");
      orb->run ();
      
      ACS_DEBUG ("acslogErrorServer", "ORB -> run");
    }
  catch( CORBA::Exception &ex )
    {
      ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
      return -1;
    }
  
  return 0;
}//startErrorServer