Ejemplo n.º 1
1
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{

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

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

        //Get reference to Root POA
        CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
        PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

        // Activate POA Manager
        PortableServer::POAManager_var mgr = poa->the_POAManager();
        mgr->activate();

        // Find the Naming Service
        obj = orb->resolve_initial_references("NameService");
        CosNaming::NamingContextExt_var root =
            CosNaming::NamingContextExt::_narrow(obj.in());
        if (CORBA::is_nil(root.in())) {
            std::cerr << "Nil Naming Context reference" << std::endl;
            return 1;
        }

        // Bind a new context.
        CosNaming::Name name;
        name.length( 1 );
        name[0].id = CORBA::string_dup( "root.esc-dot" );
        name[0].kind = CORBA::string_dup( "kind1" );

        try {
            obj = root->resolve(name);
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            CosNaming::NamingContext_var dummy = root->bind_new_context(name);
        }

        name.length( 2 );
        name[1].id = CORBA::string_dup( "leaf/esc-slash" );
        name[1].kind = CORBA::string_dup( "kind2" );

        // Create an object
        PortableServer::Servant_var<Messenger_i> servant = new Messenger_i;
        PortableServer::ObjectId_var oid = poa->activate_object(servant.in());
        CORBA::Object_var messenger_obj = poa->id_to_reference(oid.in());
        root->rebind(name, messenger_obj.in());

        // Also try rebinding to a simple path.
        CosNaming::Name_var simp_name = root->to_name("Simple");
        try {
            obj = root->resolve(simp_name.in());
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            CosNaming::NamingContext_var dummy =
                root->bind_new_context(simp_name.in());
        }
        simp_name = root->to_name("Simple/Messenger");
        root->rebind(simp_name.in(), messenger_obj.in());

        // Convert Name to String Name.
        CORBA::String_var str_name = root->to_string(name);
        std::cout << "str_name:  " << str_name.in() << std::endl;
        CORBA::String_var str_simple = root->to_string(simp_name.in());
        std::cout << "simple: " << str_simple.in() << std::endl;

        // Convert String Name to Name.
        CosNaming::Name_var tname = root->to_name(str_name.in());

        std::cout << "converted back to a CosNaming::Name: " << std::endl;
        std::cout << "   name[0] = " << (* tname)[0].id.in() << " , "
                  << (* tname)[0].kind.in() << std::endl;
        std::cout << "   name[1] = " << (* tname)[1].id.in() << " , "
                  << (* tname)[1].kind.in() << std::endl;

        // Find the application object by resolve_str.
        try {
            obj = root->resolve_str(str_name.in());
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            std::cerr<<"Couldn't resolve the string name:  " << str_name << std::endl;
            return 1;
        }

        ACE_CString base_address (":");
        base_address += ACE_TEXT_ALWAYS_CHAR (hostname);
        base_address += ":";
        base_address += ACE_TEXT_ALWAYS_CHAR (port);
        ACE_CString addr ("");
        addr = base_address + "/key/str";

        // Create an URL string for application object.
        CORBA::String_var address = CORBA::string_dup (addr.c_str());

        std::cout << "call to_url(\"" << address.in() << "\"" << std::endl;
        std::cout << "           ,\"" << str_simple.in() << "\")"<< std::endl;

        CORBA::String_var url_string = root->to_url(address.in(), str_simple.in());

        std::cout << "to_url result: " << url_string.in() << std::endl;


        // Write NS url to a file to let client read NS URL to get
        // NamingContext reference.
        CORBA::String_var ns_addr = CORBA::string_dup(base_address.c_str());

        std::cout << "call to_url(\"" <<ns_addr.in() << "\",\""
                  << str_simple.in() << "\")"<< std::endl;

        CORBA::String_var url = root->to_url(ns_addr.in(), str_simple.in());
        std::cout << "to_url result:    " << url.in() << std::endl;


        std::ofstream iorFile(ACE_TEXT_ALWAYS_CHAR (ior_output_file));
        iorFile << url.in() << std::endl;
        iorFile.close();

        std::cout << "Naming Service URL written to file " << ior_output_file << std::endl;

        // Accept requests
        orb->run();
        orb->destroy();
    }
    catch(const CORBA::Exception& ex) {
        std::cerr << "Caught a CORBA::Exception: " << ex << std::endl;
        return 1;
    }

    return 0;
}
Ejemplo n.º 2
0
int
TAO_Naming_Server::init_new_naming (CORBA::ORB_ptr orb,
                                    PortableServer::POA_ptr poa,
                                    const ACE_TCHAR *persistence_location,
                                    void *base_addr,
                                    size_t context_size,
                                    int enable_multicast,
                                    int use_storable_context,
                                    int round_trip_timeout,
                                    int use_round_trip_timeout)
{
  try
    {
#if defined (CORBA_E_MICRO)
      ACE_UNUSED_ARG (persistence_location);
      ACE_UNUSED_ARG (base_addr);
      ACE_UNUSED_ARG (use_storable_context);
#else
      if (use_storable_context)
        {
          // In lieu of a fully implemented service configurator version
          // of this Reader and Writer, let's just take something off the
          // command line for now.
          TAO::Storable_Factory* pf = 0;
          ACE_CString directory (ACE_TEXT_ALWAYS_CHAR (persistence_location));
          ACE_NEW_RETURN (pf, TAO::Storable_FlatFileFactory (directory), -1);
          auto_ptr<TAO::Storable_Factory> persFactory(pf);

          // Use an auto_ptr to ensure that we clean up the factory in the case
          // of a failure in creating and registering the Activator.
          TAO_Storable_Naming_Context_Factory* cf =
            this->storable_naming_context_factory (context_size);
          // Make sure we got a factory
          if (cf == 0) return -1;
          auto_ptr<TAO_Storable_Naming_Context_Factory> contextFactory (cf);

          // This instance will either get deleted after recreate all or,
          // in the case of a servant activator's use, on destruction of the
          // activator.

          // Was a location specified?
          if (persistence_location == 0)
            {
              // No, assign the default location "NameService"
              persistence_location = ACE_TEXT ("NameService");
            }

          // Now make sure this directory exists
          if (ACE_OS::access (persistence_location, W_OK|X_OK))
            {
              ORBSVCS_ERROR_RETURN ((LM_ERROR, "Invalid persistence directory\n"), -1);
            }

#if (TAO_HAS_MINIMUM_POA == 0) && !defined (CORBA_E_COMPACT)
          if (this->use_servant_activator_)
            {
              ACE_NEW_THROW_EX (this->servant_activator_,
                                TAO_Storable_Naming_Context_Activator (orb,
                                                                       persFactory.get(),
                                                                       contextFactory.get (),
                                                                       persistence_location),
                                CORBA::NO_MEMORY ());
              this->ns_poa_->set_servant_manager(this->servant_activator_);
            }
#endif /* TAO_HAS_MINIMUM_POA */
          try {  // The following might throw an exception.
            this->naming_context_ =
              TAO_Storable_Naming_Context::recreate_all (orb,
              poa,
              TAO_ROOT_NAMING_CONTEXT,
              context_size,
              0,
              contextFactory.get (),
              persFactory.get (),
              use_redundancy_);
          }
          catch (const CORBA::Exception& ex)
          {
            // The activator already took over the factories so we need to release the auto_ptr
            if (this->use_servant_activator_)
            {
              // The context factory is now owned by the activator
              // so we should release it
              contextFactory.release ();
              // If using a servant activator, the activator now owns the
              // factory, so we should release it
              persFactory.release ();
            }
            // Print out the exception and return failure
            ex._tao_print_exception (
              "TAO_Naming_Server::init_new_naming");
            return -1;
          }

        // Kind of a duplicate of the above here, but we must also release the
        // factory autoptrs in the good case as well.
        if (this->use_servant_activator_)
            {
              // The context factory is now owned by the activator
              // so we should release it
              contextFactory.release ();
              // If using a servant activator, the activator now owns the
              // factory, so we should release it
              persFactory.release ();
            }

      }
      else if (persistence_location != 0)
        //
        // Initialize Persistent Naming Service.
        //
        {

          // Create Naming Context Implementation Factory to be used for the creation of
          // naming contexts by the TAO_Persistent_Context_Index
          TAO_Persistent_Naming_Context_Factory *naming_context_factory =
            this->persistent_naming_context_factory ();
          // Make sure we got a factory.
          if (naming_context_factory == 0) return -1;

          // Allocate and initialize Persistent Context Index.
          ACE_NEW_RETURN (this->context_index_,
                          TAO_Persistent_Context_Index (orb, poa, naming_context_factory),
                          -1);

          if (this->context_index_->open (persistence_location,
                                          base_addr) == -1
              || this->context_index_->init (context_size) == -1)
            {
              if (TAO_debug_level >0)
                ORBSVCS_DEBUG ((LM_DEBUG,
                            "TAO_Naming_Server: context_index initialization failed\n"));
              return -1;
            }

          // Set the root Naming Context reference.
          this->naming_context_ =
            this->context_index_->root_context ();
        }
      else
#endif /* CORBA_E_MICRO */
        {
          //
          // Initialize Transient Naming Service.
          //
          this->naming_context_ =
            TAO_Transient_Naming_Context::make_new_context (poa,
                                                            TAO_ROOT_NAMING_CONTEXT,
                                                            context_size);

        }

#if !defined (CORBA_E_MICRO)
      // Register with the ORB's resolve_initial_references()
      // mechanism.  Primarily useful for dynamically loaded Name
      // Services.
      orb->register_initial_reference ("NameService",
                                       this->naming_context_.in ());
#endif /* CORBA_E_MICRO */

      // Set the ior of the root Naming Context.
      this->naming_service_ior_=
        orb->object_to_string (this->naming_context_.in ());

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

      IORTable::Table_var adapter =
        IORTable::Table::_narrow (table_object.in ());
      if (CORBA::is_nil (adapter.in ()))
        {
          ORBSVCS_ERROR ((LM_ERROR, "Nil IORTable\n"));
        }
      else
        {
          CORBA::String_var ior =
            orb->object_to_string (this->naming_context_.in ());
          adapter->bind ("NameService", ior.in ());
        }

#if defined (ACE_HAS_IP_MULTICAST)
      if (enable_multicast)
        {
          // @@ Marina: is there anyway to implement this stuff
          // without using ORB_Core_instance()? For example can you
          // pass the ORB as an argument?

          //
          // Install ior multicast handler.
          //
          // Get reactor instance from TAO.
          ACE_Reactor *reactor = orb->orb_core()->reactor ();

          // See if the -ORBMulticastDiscoveryEndpoint option was specified.
          ACE_CString mde (orb->orb_core ()->orb_params ()->mcast_discovery_endpoint ());

          // First, see if the user has given us a multicast port number
          // on the command-line;
          u_short port =
            orb->orb_core ()->orb_params ()->service_port (TAO::MCAST_NAMESERVICE);

          if (port == 0)
            {
              // Check environment var. for multicast port.
              const char *port_number =
                ACE_OS::getenv ("NameServicePort");

              if (port_number != 0)
                port = static_cast<u_short> (ACE_OS::atoi (port_number));
            }

          // Port wasn't specified on the command-line or in environment -
          // use the default.
          if (port == 0)
            port = TAO_DEFAULT_NAME_SERVER_REQUEST_PORT;

          // Instantiate a handler which will handle client requests for
          // the root Naming Context ior, received on the multicast port.
          ACE_NEW_RETURN (this->ior_multicast_,
                          TAO_IOR_Multicast (),
                          -1);

          if (mde.length () != 0)
            {
              if (this->ior_multicast_->init (this->naming_service_ior_.in (),
                                              mde.c_str (),
                                              TAO_SERVICEID_NAMESERVICE) == -1)
                return -1;
            }
          else
            {
              if (this->ior_multicast_->init (this->naming_service_ior_.in (),
                                              port,
#if defined (ACE_HAS_IPV6)
                                              ACE_DEFAULT_MULTICASTV6_ADDR,
#else
                                              ACE_DEFAULT_MULTICAST_ADDR,
#endif /* ACE_HAS_IPV6 */
                                              TAO_SERVICEID_NAMESERVICE) == -1)
                return -1;
            }

          // Register event handler for the ior multicast.
          if (reactor->register_handler (this->ior_multicast_,
                                         ACE_Event_Handler::READ_MASK) == -1)
            {
              if (TAO_debug_level > 0)
                ORBSVCS_DEBUG ((LM_DEBUG,
                            "TAO_Naming_Server: cannot register Event handler\n"));
              return -1;
            }

          if (TAO_debug_level > 0)
            ORBSVCS_DEBUG ((LM_DEBUG,
                        "TAO_Naming_Server: The multicast server setup is done.\n"));
        }
#else
  ACE_UNUSED_ARG (enable_multicast);
#endif /* ACE_HAS_IP_MULTICAST */

#if defined (TAO_HAS_CORBA_MESSAGING) && TAO_HAS_CORBA_MESSAGING != 0
      if (use_round_trip_timeout == 1)
      {
        TimeBase::TimeT roundTripTimeoutVal = round_trip_timeout;
        CORBA::Any anyObjectVal;
        anyObjectVal <<= roundTripTimeoutVal;
        CORBA::PolicyList polList (1);
        polList.length (1);
        polList[0] = orb->create_policy (Messaging::RELATIVE_RT_TIMEOUT_POLICY_TYPE,
                                         anyObjectVal);

        // set a timeout on the orb
        //
        CORBA::Object_var orbPolicyManagerObj =
          orb->resolve_initial_references ("ORBPolicyManager");

        CORBA::PolicyManager_var orbPolicyManager =
          CORBA::PolicyManager::_narrow (orbPolicyManagerObj.in ());
        orbPolicyManager->set_policy_overrides (polList, CORBA::SET_OVERRIDE);

        polList[0]->destroy ();
        polList[0] = CORBA::Policy::_nil ();
      }
#else
  ACE_UNUSED_ARG (use_round_trip_timeout);
  ACE_UNUSED_ARG (round_trip_timeout);
#endif /* TAO_HAS_CORBA_MESSAGING */
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception (
        "TAO_Naming_Server::init_new_naming");
      return -1;
    }

  return 0;
}
Ejemplo n.º 3
0
ACE_TCHAR *
ACE_OS::strenvdup (const ACE_TCHAR *str)
{
#if defined (ACE_HAS_WINCE)
  // WinCE doesn't have environment variables so we just skip it.
  return ACE_OS::strdup (str);
#elif defined (ACE_LACKS_STRENVDUP)
  ACE_UNUSED_ARG (str);
  ACE_NOTSUP_RETURN (0);
#else
  const ACE_TCHAR * start = 0;
  if ((start = ACE_OS::strchr (str, ACE_TEXT ('$'))) != 0)
    {
      ACE_TCHAR buf[ACE_DEFAULT_ARGV_BUFSIZ];
      size_t var_len = ACE_OS::strcspn (&start[1],
        ACE_TEXT ("$~!#%^&*()-+=\\|/?,.;:'\"`[]{} \t\n\r"));
      ACE_OS::strncpy (buf, &start[1], var_len);
      buf[var_len++] = ACE_TEXT ('\0');
#  if defined (ACE_WIN32)
      // Always use the ACE_TCHAR for Windows.
      ACE_TCHAR *temp = ACE_OS::getenv (buf);
#  else
      // Use char * for environment on non-Windows.
      char *temp = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (buf));
#  endif /* ACE_WIN32 */
      size_t buf_len = ACE_OS::strlen (str) + 1;
      if (temp != 0)
        buf_len += ACE_OS::strlen (temp) - var_len;
      ACE_TCHAR * buf_p = buf;
      if (buf_len > ACE_DEFAULT_ARGV_BUFSIZ)
        {
          buf_p =
            (ACE_TCHAR *) ACE_OS::malloc (buf_len * sizeof (ACE_TCHAR));
          if (buf_p == 0)
            {
              errno = ENOMEM;
              return 0;
            }
        }
      ACE_TCHAR * p = buf_p;
      size_t len = start - str;
      ACE_OS::strncpy (p, str, len);
      p += len;
      if (temp != 0)
        {
#  if defined (ACE_WIN32)
          p = ACE_OS::strecpy (p, temp) - 1;
#  else
          p = ACE_OS::strecpy (p, ACE_TEXT_CHAR_TO_TCHAR (temp)) - 1;
#  endif /* ACE_WIN32 */
        }
      else
        {
          ACE_OS::strncpy (p, start, var_len);
          p += var_len;
          *p = ACE_TEXT ('\0');
        }
      ACE_OS::strcpy (p, &start[var_len]);
      return (buf_p == buf) ? ACE_OS::strdup (buf) : buf_p;
    }
  else
    return ACE_OS::strdup (str);
#endif /* ACE_HAS_WINCE */
}
Ejemplo n.º 4
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

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

      /// Get the MC object reference that the client has exposed.
      CORBA::Object_var obj =
        orb->string_to_object (monitor_ior);

      if (CORBA::is_nil (obj.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Monitor client - string_to_object failed\n"),
                             -1);
        }

      Monitor::MC_var monitor = Monitor::MC::_narrow (obj.in ());

      if (CORBA::is_nil (monitor.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Monitor client - narrow failed\n"),
                             -1);
        }

      if (monitor_point != 0)
        {
          /// Access the monitor's value a few times and watch it grow.
          for (int i = 0; i < n_iterations; ++i)
            {
              Monitor::DataList_var data;

              if (mp_clear)
                {
                  data = monitor->get_and_clear_statistics (*monitor_point);
                }
              else
                {
                  data = monitor->get_statistics (*monitor_point);
                }

              for (CORBA::ULong index = 0; index < data->length (); ++index)
                {
                  ACE_DEBUG ((LM_DEBUG, "MP <%C>:\n", data[index].itemname.in ()));
                  Monitor::Data dlist = data[index];

                  if (dlist.data_union._d() == Monitor::DATA_TEXT)
                  {
                    for (CORBA::ULong valueindex = 0;
                         valueindex < dlist.data_union.num().dlist.length ();
                         ++valueindex)
                    {
                      Monitor::DataValue d = dlist.data_union.num().dlist[valueindex];
                      ACE_DEBUG ((LM_DEBUG, "\t value <%A>:\n", d.value));
                    }
                  }
                }

              ACE_OS::sleep (sleep_time);
            }
        }
      else
        {
          Monitor::NameList_var list = monitor->get_statistic_names (ACE_TEXT_ALWAYS_CHAR (filter));

          for (CORBA::ULong index = 0; index < list->length (); ++index)
            {
              ACE_DEBUG ((LM_DEBUG, "MP: <%C>\n", list[index].in ()));
            }
        }

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

  return 0;
}
Ejemplo n.º 5
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  MessageLog logger(HELLO_CALL_NUMBER);

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

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

      PortableGroup::GOA_var root_poa =
        PortableGroup::GOA::_narrow (poa_object.in ());

      if (CORBA::is_nil (root_poa.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Panic: nil RootPOA\n"),
                           1);

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

      // servant
      Hello_Impl* hello_impl;
      ACE_NEW_RETURN (hello_impl,
                      Hello_Impl (orb.in (), &logger),
                      1);
      PortableServer::ServantBase_var owner_transfer (hello_impl);

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

      // create UIPMC reference
      CORBA::String_var multicast_url =
        CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR(uipmc_url));
      CORBA::Object_var miop_ref =
        orb->string_to_object (multicast_url.in ());

      // create id
      PortableServer::ObjectId_var id =
        root_poa->create_id_for_reference (miop_ref.in ());

      // activate Hello Object
      root_poa->activate_object_with_id (id.in (),
                                         hello_impl);

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

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

      // If the ior_output_file exists, output the ior to it
      if (ior_output_file != 0)
        {
          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 ();

      root_poa->destroy (1, 1);

      orb->destroy ();

      if (logger.report_statistics () == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "\n (%P|%t) ERROR: No single call got through to the server\n"),
                           3);
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught in server main ():");
      return 4;
    }

  ACE_DEBUG ((LM_DEBUG,
              "\n (%P|%t) server finished successfully..\n"));
  return 0;
}
Ejemplo n.º 6
0
void
Locator_XMLHandler::startElement (const ACEXML_Char*,
                                  const ACEXML_Char*,
                                  const ACEXML_Char* qName,
                                  ACEXML_Attributes* attrs)
{
  if (ACE_OS::strcasecmp (qName, SERVER_INFO_TAG) == 0)
    {
      ACE_NEW (this->si_, Server_Info);
      this->env_vars_.clear ();

      // if attrs exists and if the previously required 9 fields
      const size_t previous_size = 9;
      if (attrs != 0 && attrs->getLength () >= previous_size)
        {
          size_t index = 0;
          this->si_->server_id = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->poa_name = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->activator = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->cmdline = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->dir = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->activation_mode_ =
            ImR_Utils::stringToActivationMode (ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++)));
          this->si_->start_limit_ = ACE_OS::atoi (attrs->getValue (index++));
          this->si_->partial_ior = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));
          this->si_->ior = ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index++));

          if (attrs->getLength () >= index)
            {
              this->server_started_ =
                (ACE_OS::atoi (attrs->getValue (index++)) != 0);
            }
          if (attrs->getLength () >= index)
            {
              this->si_->is_jacorb =
                (ACE_OS::atoi (attrs->getValue (index++)) != 0);
            }

          for ( ; index < attrs->getLength(); ++index)
            {
              ACE_TString name (attrs->getLocalName (index));
              ACE_CString value (ACE_TEXT_ALWAYS_CHAR (attrs->getValue (index)));
              if (name == KEYNAME_TAG)
                {
                  this->si_->key_name_ = value;
                }
              else if (name == ALTKEY_TAG)
                {
                  if (value.length() > 0 &&
                      this->repo_.servers ().find (value, this->si_->alt_info_) != 0)
                    {
                      Server_Info *base_si = 0;
                      ACE_NEW (base_si, Server_Info);
                      base_si->key_name_ = value;
                      this->si_->alt_info_.reset (base_si);
                      this->repo_.servers ().bind (value, this->si_->alt_info_);
                    }
                }
              else if (name == PID_TAG)
                {
                  this->si_->pid =
                    ACE_OS::atoi (attrs->getValue (index++));
                }
              else
                {
                  const ACE_CString name_cstr (ACE_TEXT_ALWAYS_CHAR (name.c_str ()));
                  this->extra_params_.push_back (std::make_pair (name_cstr, value));
                }
            }
        }
    }
  else if (ACE_OS::strcasecmp (qName, ACTIVATOR_INFO_TAG) == 0)
  {
    if (attrs != 0 && attrs->getLength () >= 3)
      {
        size_t index = 0;
        const ACE_CString aname =
          ACE_TEXT_ALWAYS_CHAR(attrs->getValue (index++));
        const ACE_TString token_str = attrs->getValue (index++);
        long token = ACE_OS::atoi (token_str.c_str ());
        const ACE_CString ior =
          ACE_TEXT_ALWAYS_CHAR(attrs->getValue (index++));
        NameValues extra_params;
        for ( ; index < attrs->getLength(); ++index)
          {
            ACE_CString name (ACE_TEXT_ALWAYS_CHAR (attrs->getLocalName(index)));
            ACE_CString value (ACE_TEXT_ALWAYS_CHAR (attrs->getValue(index)));
            extra_params.push_back (std::make_pair (name, value));
          }
        this->repo_.load_activator (aname, token, ior, extra_params);
      }
  }
  else if (ACE_OS::strcasecmp (qName, ENVIRONMENT_TAG) == 0)
    {
      if (attrs != 0 && attrs->getLength () == 2)
        {
          EnvVar ev;
          ev.name = attrs->getValue ((size_t)0);
          ev.value = attrs->getValue ((size_t)1);
          this->env_vars_.push_back (ev);
        }
    }
  else if (ACE_OS::strcasecmp (qName, PEER_TAG) == 0)
    {
      if (attrs != 0)
        {
          ACE_CString peer (ACE_TEXT_ALWAYS_CHAR (attrs->getValue((size_t)0)));
          this->peer_list_.push_back (peer);
        }
    }
}
Ejemplo n.º 7
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    Consumer_Client client;

    int status = client.init (argc, argv);
    ACE_ASSERT(status == 0);
    ACE_UNUSED_ARG(status);

    CosNotifyChannelAdmin::EventChannel_var ec =
      client.create_event_channel ("MyEventChannel", 1);

    CORBA::ORB_ptr orb = client.orb ();
    CORBA::Object_var object =
      orb->string_to_object (ior);

    sig_var sig = sig::_narrow (object.in ());

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

    CosNotifyChannelAdmin::ConsumerAdmin_var admin =
      create_consumeradmin (ec.in ());

    if (filter)
    {
      CosNotifyFilter::FilterFactory_var ffact =
        ec->default_filter_factory ();

      CosNotifyFilter::Filter_var filter =
        ffact->create_filter ("TCL");

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

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

      constraint_list[0].event_types.length (0);
      constraint_list[0].constraint_expr = CORBA::string_dup(ACE_TEXT_ALWAYS_CHAR (constraintString));

      filter->add_constraints (constraint_list);

      admin->add_filter(filter.in());
    }

    ACE_ASSERT (!CORBA::is_nil (admin.in ()));
    create_consumers(admin.in (), &client);

    // Tell the supplier to go
    sig->go ();

    client.ORB_run( );
    ACE_DEBUG((LM_DEBUG, "Consumer done.\n"));

    sig->done ();

    return 0;

  }
  catch (const CORBA::Exception& e)
  {
    e._tao_print_exception ("Error: Consumer exception: ");
  }

  return 1;
}
Ejemplo n.º 8
0
int
teardown_plan (const Options &opts,
               DAnCE::Plan_Launcher_Base *pl_base,
               const ::Deployment::DeploymentPlan *plan,
               CORBA::ORB_ptr orb)
{
  DANCE_TRACE ("teardown_plan");

  int rc = 0;
  try
    {
      CORBA::Object_var am;
      CORBA::Object_var app;
      if (opts.am_ior_ && opts.app_ior_)
        {
          DANCE_DEBUG (DANCE_LOG_MAJOR_EVENT,
                       (LM_DEBUG, DLINFO
                        ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                        ACE_TEXT ("Tearing down plan with explicitly ")
                        ACE_TEXT ("nominated App and AM IORs.\n")));
          am = orb->string_to_object (opts.am_ior_);
          app = orb->string_to_object (opts.app_ior_);
        }
      else
        {
          // Need to perform lookup by uuid,
          // either explicitly provided or in plan.
          ACE_CString uuid;
          if (plan)
            uuid = plan->UUID.in ();
          else
            uuid = ACE_TEXT_ALWAYS_CHAR (opts.uuid_);

          DAnCE::EM_Launcher *em_launcher =
            dynamic_cast <DAnCE::EM_Launcher *> (pl_base);

          if (!em_launcher)
            {
              DANCE_ERROR (DANCE_LOG_TERMINAL_ERROR,
                           (LM_ERROR, DLINFO
                            ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                            ACE_TEXT ("Error: Attempting UUID lookup on non")
                            ACE_TEXT ("-EM managed plan not supported\n")));
              return 1;
            }

          if (em_launcher->lookup_by_uuid (uuid.c_str (),
                                           am.out (),
                                           app.out ()))
            {
              DANCE_DEBUG (DANCE_LOG_MAJOR_EVENT,
                           (LM_DEBUG, DLINFO
                            ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                            ACE_TEXT ("Tearing down plan with UUID %C\n"),
                            uuid.c_str ()));
            }
          else
            {
              DANCE_ERROR (DANCE_LOG_TERMINAL_ERROR,
                           (LM_ERROR, DLINFO
                            ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                            ACE_TEXT ("Error: Lookup by UUID failed\n")));
              return 1;
            }
        }

      try
        {
          pl_base->teardown_application (am, app);
        }
      catch (const DAnCE::Deployment_Failure &ex)
        {
          if (!opts.quiet_)
            {
              DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                        ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                        ACE_TEXT ("Application Teardown failed, exception: %C\n"),
                        ex.ex_.c_str ()));
            }
          rc = 1;
        }
      catch (const CORBA::Exception &ex)
        {
          if (!opts.quiet_)
            {
              DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                          ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                          ACE_TEXT ("Application Teardown failed, ")
                          ACE_TEXT ("caught CORBA exception %C\n"),
                          ex._info ().c_str ()));
            }
          rc = 1;
        }
      catch (...)
        {
          if (!opts.quiet_)
            {
              DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                          ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                          ACE_TEXT ("Application Teardown failed, ")
                          ACE_TEXT ("caught unknown C++ exception\n")));
            }
          rc = 1;
        }

      if (rc == 0 || opts.force_)
        pl_base->destroy_app_manager (am);
    }
  catch (const DAnCE::Deployment_Failure &ex)
    {
      if (!opts.quiet_)
        {
          DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                      ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                      ACE_TEXT ("Teardown failed, exception: %C\n"),
                      ex.ex_.c_str ()));
        }
      return 1;
    }
  catch (const CORBA::Exception &ex)
    {
      if (!opts.quiet_)
        {
          DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                      ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                      ACE_TEXT ("Teardown failed, caught CORBA exception %C\n"),
                      ex._info ().c_str ()));
        }
      return 1;
    }
  catch (...)
    {
      if (!opts.quiet_)
        {
          DANCE_ERROR (DANCE_LOG_EMERGENCY, (LM_ERROR, DLINFO
                      ACE_TEXT ("Plan_Launcher::teardown_plan - ")
                      ACE_TEXT ("Teardown failed, ")
                      ACE_TEXT ("caught unknown C++ exception\n")));
        }
      return 1;
    }

  return rc;
}
Ejemplo n.º 9
0
bool
RPG_Net_Server_Common_Tools::getNextLogFilename (const std::string& directory_in,
                                                 std::string& FQLogFilename_out)
{
  RPG_TRACE (ACE_TEXT ("RPG_Net_Server_Common_Tools::getNextLogFilename"));

  // initialize return value(s)
  FQLogFilename_out.resize (0);

  // sanity check(s): log directory exists ?
  // No ? --> try to create it then !
  if (!Common_File_Tools::isDirectory (directory_in))
  {
    if (!Common_File_Tools::createDirectory (directory_in))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to Common_File_Tools::createDirectory(\"%s\"), aborting\n"),
                  ACE_TEXT (directory_in.c_str ())));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
               ACE_TEXT ("created directory: \"%s\"...\n"),
               ACE_TEXT (directory_in.c_str ())));
  } // end IF

  // construct correct logfilename...
  FQLogFilename_out = directory_in;
  FQLogFilename_out += ACE_DIRECTORY_SEPARATOR_CHAR_A;
  std::string logFileName = ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
  logFileName += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
  FQLogFilename_out += logFileName;

  // retrieve all existing logs and sort them alphabetically...
  ACE_Dirent_Selector entries;
  int result = entries.open (directory_in.c_str (),
                             &RPG_Net_Server_Common_Tools::selector,
                             &RPG_Net_Server_Common_Tools::comparator);
  if (result == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE_Dirent_Selector::open(\"%s\"): \"%s\", aborting\n"),
                ACE_TEXT (directory_in.c_str ()),
                ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error()))));
    return false;
  } // end IF

//   ACE_DEBUG ((LM_DEBUG,
//               ACE_TEXT ("found %d logfiles...\n"),
//               entries.length ()));

  // OK: iterate over the entries and perform some magic...
  // *NOTE*: entries have been sorted alphabetically:
  //         1 current 2 4 3 --> current 1 2 3 4
  // *TODO*: some malicious user could inject "fake" logfiles which can
  //         "confuse" this algorithm...
  // skip handling of "<PREFIX><SUFFIX>" (if found)...
  // *NOTE*: <PREFIX><SUFFIX> will become <PREFIX>_1<SUFFIX>...
  bool found_current = false;
  // sscanf settings
  int number = 0;
  int return_val = -1;
  std::string format_string ("%d");
  format_string += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
  std::stringstream converter;
  for (int i = entries.length () - 1, index = RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_ - 1;
       i >= 0;
       i--)
  {
    // perform "special treatment" if "<PREFIX><SUFFIX>" found...
    // *TODO*: do this in C++...
    if (ACE_OS::strcmp (entries[i]->d_name,
                        logFileName.c_str ()) == 0)
    {
      found_current = true;

      // skip this one for now
      continue;
    } // end IF

    // scan number...
    try
    {
      // *TODO*: do this in C++...
      return_val = ::sscanf (entries[i]->d_name +
                             // skip some characters...
                             (ACE_OS::strlen (ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX)) + 1),
                             format_string.c_str (),
                             &number);
      if (return_val != 1)
      {
        if (return_val != 0)
        {
          ACE_DEBUG ((LM_ERROR,
                      ACE_TEXT ("::sscanf() failed for \"%s\": \"%s\", continuing\n"),
                      entries[i]->d_name,
                      ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));
        } // end IF

        continue;
      } // end IF
    }
    catch (...)
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("caught exception in ::sscanf() for \"%s\": \"%s\", continuing\n"),
                  entries[i]->d_name,
                  ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));

      continue;
    }

    // adjust the index, if the number is smaller than max
    if (number < index)
      index = number + 1;

    // if the number is bigger than the max AND we have more than enough logs --> delete it !
    if ((static_cast<unsigned long> (number) >= (RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_ - 1)) &&
        (static_cast<unsigned long> (entries.length()) >= RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_))
    {
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("removing surplus logfile \"%s\"...\n"),
                  entries[i]->d_name));

      // clean up
      std::string FQfilename = directory_in;
      FQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
      FQfilename += entries[i]->d_name;
      Common_File_Tools::deleteFile (FQfilename);

      continue;
    } // end IF

    // logrotate file...
    std::string oldFQfilename = directory_in;
    oldFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    oldFQfilename += entries[i]->d_name;

    std::string newFQfilename = directory_in;
    newFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
    newFQfilename += ACE_TEXT_ALWAYS_CHAR ("_");

    converter.clear ();
    converter.str (ACE_TEXT_ALWAYS_CHAR (""));
    converter << index;

    newFQfilename += converter.str ();
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
    // *IMPORTANT NOTE*: last parameter affects Win32 behaviour only,
    // see "ace/OS_NS_stdio.inl" !
    if (ACE_OS::rename (oldFQfilename.c_str (),
                        newFQfilename.c_str (),
                        -1))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE_OS::rename() \"%s\" to \"%s\": \"%s\", aborting\n"),
                  ACE_TEXT (oldFQfilename.c_str ()),
                  ACE_TEXT (newFQfilename.c_str ()),
                  ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("renamed file \"%s\" to \"%s\"...\n"),
                ACE_TEXT (oldFQfilename.c_str ()),
                ACE_TEXT (newFQfilename.c_str ())));

    index--;
  } // end FOR

  if (found_current)
  {
    std::string newFQfilename = directory_in;
    newFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
    newFQfilename += ACE_TEXT_ALWAYS_CHAR ("_1");
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);

    // *TODO*: last parameter affects Win32 behaviour only, see "ace/OS_NS_stdio.inl" !
    if (ACE_OS::rename (FQLogFilename_out.c_str (),
                        newFQfilename.c_str (),
                        -1))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE_OS::rename() \"%s\" to \"%s\": \"%m\", aborting\n"),
                  ACE_TEXT (FQLogFilename_out.c_str ()),
                  ACE_TEXT (newFQfilename.c_str ())));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("renamed file \"%s\" to \"%s\"...\n"),
                ACE_TEXT (FQLogFilename_out.c_str ()),
                ACE_TEXT (newFQfilename.c_str ())));
  } // end IF

  return true;
}
Ejemplo n.º 10
0
int
ECT_Consumer_Driver::parse_args (int argc, ACE_TCHAR *argv [])
{
  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("xdc:s:h:p:o:"));
  int opt;

  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
        case 'x':
          this->shutdown_event_channel_ = 0;
          break;

        case 'c':
          this->n_consumers_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 's':
          this->n_suppliers_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 'h':
          {
            char* aux;
                char* arg = ACE_OS::strtok_r (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()), ",", &aux);

            this->type_start_ = ACE_ES_EVENT_UNDEFINED + ACE_OS::atoi (arg);
                arg = ACE_OS::strtok_r (0, ",", &aux);
            this->type_count_ = ACE_OS::atoi (arg);
          }
          break;

        case 'p':
          this->pid_file_name_ = get_opt.opt_arg ();
          break;

        case 'o':
          this->stall_length_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case '?':
        default:
          ACE_DEBUG ((LM_DEBUG,
                      "Usage: %s "
                      "[ORB options] "
                      "-d -x "
                      "-c <n_consumers> "
                      "-s <n_suppliers> "
                      "-h <type_start,type_count> "
                      "-p <pid file name> "
                      "\n",
                      argv[0]));
          return -1;
        }
    }

  if (this->n_suppliers_ <= 0)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "%s: number of suppliers (%d) is out of range, "
                  "reset to default (%d)\n",
                  argv[0], this->n_suppliers_,
                  1));
      this->n_suppliers_ = 1;
    }

  if (this->n_consumers_ <= 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         "%s: number of consumers or "
                         "suppliers out of range\n", argv[0]), -1);
    }

  if (this->type_count_ <= 0)
    {
      this->type_count_ = 1;
      ACE_ERROR_RETURN ((LM_ERROR,
                         "%s: number of event types "
                         "suppliers out of range, reset to default (1)\n",
                         argv[0]), -1);
    }

  return 0;
}
int
ACE_Logging_Strategy::handle_timeout (const ACE_Time_Value &,
                                      const void *)
{
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
  if ((size_t) ACE_OS::fseek (this->log_msg_->msg_ostream (),
                              0,
                              SEEK_CUR) > this->max_size_)
#else
  if ((size_t) this->log_msg_->msg_ostream ()->tellp () 
      > this->max_size_)
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */
    {
      // Lock out any other logging.
      if (this->log_msg_->acquire ())
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_LIB_TEXT ("Cannot acquire lock!\n")),
                          -1);

      // Close the current ostream.
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
      FILE *output_file = (FILE *) this->log_msg_->msg_ostream ();
      ACE_OS::fclose (output_file);
      // We'll call msg_ostream() modifier later.
#else
      ofstream *output_file = 
        (ofstream *) this->log_msg_->msg_ostream ();
      output_file->close ();
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */
      // Save current logfile to logfile.old analyze if it was set any
      // fixed number for the log_files.
      if (fixed_number_)
        {
          if (max_file_number_ < 1) //we only want one file
            {
              // Just unlink the file.
              ACE_OS::unlink (this->filename_);

              // Open a new log file with the same name.
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
              output_file = ACE_OS::fopen (this->filename_,
                                           ACE_LIB_TEXT ("wt"));

              if (output_file == 0)
                return -1;

              this->log_msg_->msg_ostream (output_file);
#else
              output_file->open (ACE_TEXT_ALWAYS_CHAR (this->filename_),
                                 ios::out);
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */

              // Release the lock previously acquired.
              this->log_msg_->release ();
              return 0;
            }
        }
      count_++;

      // Set the number of digits of the log_files labels.
      int digits = 1, res = count_;
      while((res = (res / 10))>0)
        digits++;

      if (ACE_OS::strlen (this->filename_) + digits <= MAXPATHLEN)
        {
          ACE_TCHAR backup[MAXPATHLEN+1];

          // analyse if it was chosen the mode which will order the
          // log_files
          if (order_files_)
            {
              ACE_TCHAR to_backup[MAXPATHLEN+1];

              // reorder the logs starting at the oldest (the biggest
              // number) watch if we reached max_file_number_.
              int max_num;
              if (fixed_number_ && count_ > max_file_number_)
                // count_ will always be bigger than max_file_number_,
                // so do nothing so to always reorder files from
                // max_file_number_.
                max_num = max_file_number_;
              else
                max_num = count_;

              for (int i = max_num ; i > 1 ;i--)
                {
                  ACE_OS::sprintf (backup,
                                   ACE_LIB_TEXT ("%s.%d"),
                                   this->filename_,
                                   i);
                  ACE_OS::sprintf (to_backup,
                                   ACE_LIB_TEXT ("%s.%d"),
                                   this->filename_,
                                   i - 1);

                  // Remove any existing old file; ignore error as
                  // file may not exist.
                  ACE_OS::unlink (backup);

                  // Rename the current log file to the name of the
                  // backup log file.
                  ACE_OS::rename (to_backup, backup);
                }
              ACE_OS::sprintf (backup,
                               ACE_LIB_TEXT ("%s.1"),
                               this->filename_);
            }
          else
            {
              if (fixed_number_ && count_>max_file_number_) 
                count_ = 1; // start over from 1

              ACE_OS::sprintf (backup,
                               ACE_LIB_TEXT ("%s.%d"),
                               this->filename_,
                               count_);
            }

          // Remove any existing old file; ignore error as file may
          // not exist.
          ACE_OS::unlink (backup);

          // Rename the current log file to the name of the backup log
          // file.
          ACE_OS::rename (this->filename_, backup);
        }
      else
        ACE_ERROR ((LM_ERROR,
                    ACE_LIB_TEXT ("Backup file name too long; ")
                    ACE_LIB_TEXT ("backup logfile not saved.\n")));

      // Open a new log file by the same name
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
      output_file = ACE_OS::fopen (this->filename_, ACE_LIB_TEXT ("wt"));

      if (output_file == 0)
        return -1;

      this->log_msg_->msg_ostream (output_file);
#else
      output_file->open (ACE_TEXT_ALWAYS_CHAR (this->filename_),
                         ios::out);
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */

      // Release the lock previously acquired.
      this->log_msg_->release ();
    }

  return 0;
}
int
ACE_Logging_Strategy::init (int argc, ACE_TCHAR *argv[])
{
  ACE_TRACE ("ACE_Logging_Strategy::init");

  // Store current priority masks for changes in <parse_args>.

  this->process_priority_mask_ =
    this->log_msg_->priority_mask (ACE_Log_Msg::PROCESS);

  this->thread_priority_mask_ =
    this->log_msg_->priority_mask (ACE_Log_Msg::THREAD);

  // Use the options hook to parse the command line arguments.
  this->parse_args (argc, argv);

  // Setup priorities (to original if not specified on command line)

  this->log_msg_->priority_mask (thread_priority_mask_,
                                 ACE_Log_Msg::THREAD);

  this->log_msg_->priority_mask (process_priority_mask_,
                                 ACE_Log_Msg::PROCESS);

  // Check if any flags were specified. If none were specified, let
  // the default behavior take effect.
  if (this->flags_ != 0)
    {
      // Clear all flags
      this->log_msg_->clr_flags (ACE_Log_Msg::STDERR
                                | ACE_Log_Msg::LOGGER
                                | ACE_Log_Msg::OSTREAM
                                | ACE_Log_Msg::VERBOSE
                                | ACE_Log_Msg::VERBOSE_LITE
                                | ACE_Log_Msg::SILENT
                                | ACE_Log_Msg::SYSLOG);
      // Check if OSTREAM bit is set
      if (ACE_BIT_ENABLED (this->flags_,
                           ACE_Log_Msg::OSTREAM))
        {
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
          FILE *output_file = 0;
          if (wipeout_logfile_)
            output_file = ACE_OS::fopen (this->filename_, ACE_LIB_TEXT ("wt"));
          else
            output_file = ACE_OS::fopen (this->filename_, ACE_LIB_TEXT ("at"));
          if (output_file == 0)
            return -1;
#else
          ofstream *output_file = 0;
          // Create a new ofstream to direct output to the file.
          if (wipeout_logfile_)
            ACE_NEW_RETURN 
              (output_file,
               ofstream (ACE_TEXT_ALWAYS_CHAR (this->filename_)),
               -1);
          else
            ACE_NEW_RETURN 
              (output_file,
               ofstream (ACE_TEXT_ALWAYS_CHAR (this->filename_),
                         ios::app | ios::out),
               -1);
          if (output_file->rdstate () != ios::goodbit)
            {
              delete output_file;
              return -1;
            }
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */
          // Set the <output_file> that'll be used by the rest of the
          // code.
          this->log_msg_->msg_ostream (output_file);

          // Setup a timeout handler to perform the maximum file size
          // check (if required).
          if (this->interval_ > 0 && this->max_size_ > 0)
            {
              if (this->reactor () == 0)
                // Use singleton.
                this->reactor (ACE_Reactor::instance ());  

              this->reactor ()->schedule_timer 
                (this, 0,
                 ACE_Time_Value (this->interval_),
                 ACE_Time_Value (this->interval_));
            }
        }
      // Now set the flags for Log_Msg
      this->log_msg_->set_flags (this->flags_);
    }

  return this->log_msg_->open (this->program_name_,
                               this->log_msg_->flags (),
                               this->logger_key_);
}
Ejemplo n.º 13
0
std::string Directory::name() const
{
  return ACE_TEXT_ALWAYS_CHAR(logical_dirname_.c_str());
}
Ejemplo n.º 14
0
std::string File::name() const
{
  return ACE_TEXT_ALWAYS_CHAR(logical_relative_.c_str());
}
Ejemplo n.º 15
0
void
TAO_Notify_Tests_Filter_Command::init (ACE_Arg_Shifter& arg_shifter)
{
  if (arg_shifter.is_anything_left ())
    {
      if (arg_shifter.cur_arg_strncasecmp (ACE_TEXT("-CreateFactory")) == 0) // -Create factory_name ec
        {
          this->command_ = CREATE_FACTORY;

          arg_shifter.consume_arg ();

          this->name_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); // FF name
          arg_shifter.consume_arg ();

          this->factory_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); //EC
          arg_shifter.consume_arg ();
        }
      else if (arg_shifter.cur_arg_strncasecmp (ACE_TEXT("-CreateFilter")) == 0) // -CreateFilter filter_name filterfactory_name
        {
          this->command_ = CREATE_FILTER;

          arg_shifter.consume_arg ();

          this->name_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); // Filter name

          arg_shifter.consume_arg ();

          this->factory_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); //FF
          arg_shifter.consume_arg ();
        }
      else if (arg_shifter.cur_arg_strncasecmp (ACE_TEXT("-Add_Constraint")) == 0) // -Add_Constraint filter_name constraint_expr
        {
          this->command_ = ADD_CONSTRAINT;

          arg_shifter.consume_arg ();

          this->name_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); // Filter name

          arg_shifter.consume_arg ();

          this->constraint_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); //Constraint
          arg_shifter.consume_arg ();
        }
      else if (arg_shifter.cur_arg_strncasecmp (ACE_TEXT("-Add_Filter")) == 0) // -Add_Filter filter_name FilterAdmin_Name
        {
          this->command_ = ADD_FILTER;

          arg_shifter.consume_arg ();

          this->name_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); // Filter name

          arg_shifter.consume_arg ();

          this->factory_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); //FilterAdmin
          arg_shifter.consume_arg ();
        }
      else if (arg_shifter.cur_arg_strncasecmp (ACE_TEXT("-Destroy")) == 0) // -Destroy filter_name
        {
          this->command_ = DESTROY;

          arg_shifter.consume_arg ();

          this->name_ = ACE_TEXT_ALWAYS_CHAR(arg_shifter.get_current ()); // filter

          arg_shifter.consume_arg ();
        }
    }
}
Ejemplo n.º 16
0
void
XML_Parser::parseFile(const std::string& emitClassQualifier_in,
                      const bool& emitStringConversionUtilities_in,
                      const bool& emitTaggedUnions_in,
                      const std::string& filename_in,
                      const bool& generateIncludeHeader_in,
                      const std::string& directory_in,
                      const std::string& preambleFilename_in,
                      const bool& filePerDefinition_in,
                      const std::string& typePrefix_in,
                      const std::string& typePostfix_in,
                      const bool& validate_in)
{
  ACE_TRACE(ACE_TEXT("XML_Parser::parseFile"));

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("parsing (XML) file \"%s\"...\n"),
             filename_in.c_str()));

  // Create a SAX parser object. Then, according to what we were told on
  // the command line, set it to validate or not
  SAX2XMLReader* reader = NULL;
  try
  {
    reader = XMLReaderFactory::createXMLReader();
  }
  catch (...)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught exception in XMLReaderFactory::createXMLReader, returning\n")));

    return;
  }
  if (!reader)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("failed to XMLReaderFactory::createXMLReader, returning\n")));

    return;
  } // end IF

  // Then, according to what we were told on
  // the command line, set it to validate or not.
  if (validate_in)
  {
    // "automatic" validation...
    reader->setFeature(XMLUni::fgSAX2CoreValidation, true);
    reader->setFeature(XMLUni::fgXercesDynamic, true);
//     reader->setFeature(XMLUni::fgXercesDynamic, false);
  } // end IF
  else
  {
    reader->setFeature(XMLUni::fgSAX2CoreValidation, false);
  } // end ELSE

  reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
  reader->setFeature(XMLUni::fgXercesSchema, true);
//   reader->setFeature(XMLUni::fgXercesHandleMultipleImports, true);
  reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
  reader->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);

  // Create the handler object and install it as the document and error
  // handler for the parser. Then parse the file and catch any exceptions
  // that propogate out
  int errorCount = 0;
  std::string schemaFilename = ACE::basename(filename_in.c_str());
  std::string preamble;
  ACE_stat stat;
  if (!preambleFilename_in.empty() &&
      (ACE_OS::stat(preambleFilename_in.c_str(), &stat) != -1)) // exists ?
  {
    std::ifstream preambleStream(preambleFilename_in.c_str(), std::ios_base::in);
    if (!preambleStream.is_open())
    {
      ACE_DEBUG((LM_ERROR,
                 ACE_TEXT("failed to open preamble file: \"%s\", returning\n"),
                 preambleFilename_in.c_str()));

      return;
    } // end IF
    std::string line;
    while (std::getline(preambleStream, line))
    {
      preamble += line;
      preamble += ACE_TEXT_ALWAYS_CHAR("\n");
    } // end WHILE
    preambleStream.close();
  } // end IF
  XML_Handler handler(emitClassQualifier_in,
                      emitStringConversionUtilities_in,
                      emitTaggedUnions_in,
                      schemaFilename,
                      generateIncludeHeader_in,
                      directory_in,
                      preamble,
                      filePerDefinition_in,
                      typePrefix_in,
                      typePostfix_in);
  try
  {
    reader->setContentHandler(&handler);
    reader->setErrorHandler(&handler);
    reader->parse(filename_in.c_str());
    errorCount = reader->getErrorCount();
  }
  catch (const OutOfMemoryException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught OutOfMemoryException: \"%s\", returning\n"),
			   message));

		// clean up
		XMLString::release(&message);
		delete reader;
    reader = NULL;

    return;
  }
  catch (const XMLException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught XMLException: \"%s\", returning\n"),
               message));

    // clean up
    XMLString::release(&message);
    delete reader;
    reader = NULL;

    return;
  }
  catch (const SAXParseException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught SAXParseException: \"%s\", returning\n"),
               message));

    // clean up
    XMLString::release(&message);
    delete reader;
    reader = NULL;

    return;
  }
  catch (...)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("SAX2XMLReader: caught exception, returning\n")));

    // clean up
    delete reader;
    reader = NULL;

    return;
  }

  // Delete the parser itself. Must be done prior to calling Terminate
  delete reader;
  reader = NULL;

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("parsing (XML) file \"%s\"...finished (%d errors)\n"),
             ACE_TEXT(filename_in.c_str()),
             errorCount));
}
Ejemplo n.º 17
0
int ACE_TMAIN (int argc, ACE_TCHAR* argv[])
{
  try
    {
      // First initialize the ORB, that will remove some arguments...
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (argc < 2)
        {
          ACE_DEBUG ((LM_DEBUG, "\nUsage:\n  %s [NAME to insert in Naming Service]\n", argv[0]));
          return -1;
        }
      // Get a reference to the RootPOA
      CORBA::Object_var poa_object =
        orb->resolve_initial_references ("RootPOA");

      // narrow down to the correct reference
      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (poa_object.in ());

      // Set a POA Manager
      PortableServer::POAManager_var poa_manager =
        poa->the_POAManager ();

      // Activate the POA Manager
      poa_manager->activate ();

      // Create the servant
      corbaloc_Status_i status_i;
      status_i.set_name (ACE_TEXT_ALWAYS_CHAR (argv[1]));
      // Activate it to obtain the reference
      PortableServer::ObjectId_var id =
        poa->activate_object (&status_i);

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

      corbaloc::Status_var status =
        corbaloc::Status::_narrow (object.in ());

      // Get a reference to Naming Context
      CORBA::Object_var naming_context_object =
        orb->resolve_initial_references ("NameService");

      // Narrow down the reference
      CosNaming::NamingContext_var naming_context =
        CosNaming::NamingContext::_narrow (naming_context_object.in ());

      // Bind Iterator_Factory to the Naming Context
      CosNaming::Name name (1);
      name.length (1);
      name[0].id = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (argv[1]));

      naming_context->rebind (name, status.in ());

      // Run the orb
      orb->run ();

      // Destroy the POA, waiting until the destruction terminates
      poa->destroy (1, 1);
      orb->destroy ();
    }
  catch (const CORBA::SystemException& ex){
    ex._tao_print_exception ("CORBA exception raised! ");
  }
  catch (const CORBA::Exception& ex){
    ex._tao_print_exception ("Exception caught in server");
  }

  return 0;
}
int ReplicationManagerFaultConsumerAdapter::parse_args (int argc, ACE_TCHAR * argv[])
{
  int optionError = 0;
  ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("o:r:d:n:"));
  int c;
  while ((c = get_opts ()) != -1)
  {
    switch (c)
    {
      case 'r':
      {
        this->replica_iors_.push_back (ACE_TEXT_ALWAYS_CHAR(get_opts.opt_arg ()));
        break;
      }
      case 'd':
      {
        this->detector_ior_ = get_opts.opt_arg ();
        break;
      }
      case 'n':
      {
        this->notifier_ior_ = get_opts.opt_arg ();
        break;
      }
      case 'o':
      {
        this->readyFile_ = get_opts.opt_arg ();
        break;
      }

      default:
        // fall thru
      case '?':
      {
        break;
      }
    }
  }

  if(! optionError)
  {
    if (0 == this->replica_iors_.size())
    {
      ACE_ERROR ((LM_ERROR,
        "-r option is required.\n"
        ));
      optionError = -1;
    }
    if (0 == this->detector_ior_)
    {
      ACE_ERROR ((LM_ERROR,
        "-d option is required.\n"
        ));
      optionError = -1;
    }
  }

  if(optionError)
  {
    ACE_ERROR ((LM_ERROR,
      "usage:  %s"
      " -r <replica.ior[ -r replica.ior]>"
      " -d <detector.ior>"
      " -o <this.ior>"
      " -n <nameService name>"
      "\n",
      argv [0]
      ));
  }
  return optionError;
}
Ejemplo n.º 19
0
int
Event_Service::parse_args (int argc, ACE_TCHAR* argv [])
{
  // default values...
  this->service_name_ = "EventService";

  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("an:o:p:s:q:bx"));
  int opt;

  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
        case 'a':
          // This is processed in main()
          break;
        case 'n':
          this->service_name_ = ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ());
          break;

        case 'o':
          this->ior_file_name_ = get_opt.opt_arg ();
          break;

        case 'p':
          this->pid_file_name_ = get_opt.opt_arg ();
          break;

        case 'q':
          this->object_id_ = ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ());
          break;

        case 'b':
          this->use_bidir_giop_ = true;
          break;

        case 'x':
          this->bind_to_naming_service_ = false;
          break;

        case 's':
          // It could be just a flag (i.e. no "global" or "local"
          // argument, but this is consistent with the EC_Multiple
          // test and also allows for a runtime scheduling service.

          if (ACE_OS::strcasecmp (get_opt.opt_arg (), ACE_TEXT("global")) == 0)
            {
              this->scheduler_type_ = ES_SCHED_GLOBAL;
            }
          else if (ACE_OS::strcasecmp (get_opt.opt_arg (), ACE_TEXT("local")) == 0)
            {
              this->scheduler_type_ = ES_SCHED_LOCAL;
            }
          else if (ACE_OS::strcasecmp (get_opt.opt_arg (), ACE_TEXT("none")) == 0)
            {
              this->scheduler_type_ = ES_SCHED_NONE;
            }
          else
            {
              ORBSVCS_DEBUG ((LM_DEBUG,
                          ACE_TEXT("Unknown scheduling type <%s> ")
                          ACE_TEXT("defaulting to none\n"),
                          get_opt.opt_arg ()));
              this->scheduler_type_ = ES_SCHED_NONE;
            }
          break;

        case '?':
        default:
          ORBSVCS_DEBUG ((LM_DEBUG,
                      ACE_TEXT("Usage: %s ")
                      ACE_TEXT("-a ")
                      ACE_TEXT("-n service_name ")
                      ACE_TEXT("-o ior_file_name ")
                      ACE_TEXT("-p pid_file_name ")
                      ACE_TEXT("-s <global|local|none> ")
                      ACE_TEXT("-q ec_object_id ")
                      ACE_TEXT("-x [disable naming service bind] ")
                      ACE_TEXT("-b [use bidir giop] ")
                      ACE_TEXT("\n"),
                      argv[0]));
          return -1;
        }
    }

  return 0;
}
Ejemplo n.º 20
0
void
CCD_Handler::component_interface_descr (
    const ComponentInterfaceDescription &desc,
    Deployment::ComponentInterfaceDescription& toconfig)
{
    DANCE_TRACE("CCD_Handler::component_interface_descr");
    if (desc.UUID_p ())
        toconfig.UUID =
            CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (desc.UUID ().c_str ()));

    if (desc.label_p ())
    {
        toconfig.label =
            CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (desc.label ().c_str ()));
    }

    if (desc.specificType_p ())
    {
        toconfig.specificType =
            CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (desc.specificType ().c_str ()));
    }

    ComponentInterfaceDescription::supportedType_const_iterator
    end = desc.end_supportedType ();

    CORBA::ULong pos = 0;
    toconfig.supportedType.length (desc.count_supportedType ());
    for (ComponentInterfaceDescription::supportedType_const_iterator s =
                desc.begin_supportedType ();
            s != end;
            ++s)
    {
        toconfig.supportedType[pos++] = ACE_TEXT_ALWAYS_CHAR ((*s)->c_str ());
    }

    ComponentInterfaceDescription::idlFile_const_iterator
    eidl = desc.end_idlFile ();
    pos = 0;
    toconfig.idlFile.length (desc.count_idlFile ());
    for (ComponentInterfaceDescription::idlFile_const_iterator sidl=
                desc.begin_idlFile ();
            sidl != eidl;
            ++sidl)
    {
        toconfig.idlFile [pos++] = ACE_TEXT_ALWAYS_CHAR ((*sidl)->c_str ());
    }

    ComponentInterfaceDescription::configProperty_const_iterator pend =
        desc.end_configProperty ();
    pos = 0;
    toconfig.configProperty.length (desc.count_configProperty ());
    for (ComponentInterfaceDescription::configProperty_const_iterator pstart =
                desc.begin_configProperty ();
            pstart != pend;
            ++pstart)
    {
        Property_Handler::handle_property (*(*pstart),
                                           toconfig.configProperty [pos++]);
    }

    pos = 0;
    toconfig.port.length (desc.count_port ());
    for (ComponentInterfaceDescription::port_const_iterator
            port (desc.begin_port ());
            port != desc.end_port ();
            ++port)
    {
        CPD_Handler::handle_component_port_description (*(*port),
                toconfig.port[pos++]);
    }

    pos = 0;
    CORBA::ULong len = desc.count_property ();
    toconfig.property.length ( len );
    for(ComponentInterfaceDescription::property_const_iterator
            prop (desc.begin_property());
            prop != desc.end_property();
            prop++)
    {
        ComponentPropertyDescription_Handler::component_property_description (*(*prop),
                toconfig.property[pos++]);
    }

    pos = 0;
    toconfig.infoProperty.length (desc.count_infoProperty ());
    for ( ComponentInterfaceDescription::infoProperty_const_iterator
            infoProp (desc.begin_infoProperty());
            infoProp != desc.end_infoProperty();
            infoProp++)
    {
        Property_Handler::handle_property (*(*infoProp),
                                           toconfig.infoProperty[pos]);
    }
}
Ejemplo n.º 21
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

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

    const ACE_TCHAR *ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR *address = ACE_TEXT ("localhost");
    const ACE_TCHAR *iorfile = 0;
    u_short port = 12345;
    u_short listenport = 12345;

    int mcast = 1;

    for (int i = 0; argv[i] != 0; i++)
      {
        if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-ecname")) == 0)
          {
            if (argv[i+1] != 0)
                ecname = argv[++i];
            else
              ACE_ERROR_RETURN ((LM_ERROR,  "Missing Event channel name\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-address")) == 0)
          {
            if (argv[i+1] != 0)
              address = argv[++i];
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing address\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-port")) == 0)
          {
            if (argv[i+1] != 0)
              port = ACE_OS::atoi(argv[++i]);
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing port\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-listenport")) == 0)
          {
            if (argv[i+1] != 0)
              listenport = ACE_OS::atoi(argv[++i]);
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing port\n"), 0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-iorfile")) == 0)
          {
            if (argv[i+1] != 0)
              iorfile = argv[++i];
             else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing ior file\n"), 0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-udp")) == 0)
          mcast = 0;
      }

    // Get the POA
    CORBA::Object_var tmpobj = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (tmpobj.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Create a local event channel and register it
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    TAO_EC_Event_Channel ec_impl (attributes);
    ec_impl.activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(&ec_impl);
    tmpobj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(tmpobj.in());

    // Find the Naming Service.
    tmpobj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context =
      CosNaming::NamingContextExt::_narrow(tmpobj.in());

    // Bind the Event Channel using Naming Services
    CosNaming::Name_var name =
      root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a proxy push consumer from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
      admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    EchoEventSupplier_i servant(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(&servant);
    tmpobj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(tmpobj.in());

    // Connect to the EC.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    consumer->connect_push_supplier (supplier.in (), qos.get_SupplierQOS ());

    // Initialize the address server with the desired address. This will
    // be used by the sender object and the multicast receiver only if
    // one is not otherwise available via the naming service.
    ACE_INET_Addr send_addr (port, address);
    SimpleAddressServer addr_srv_impl (send_addr);

    // Create an instance of the addr server for local use

    PortableServer::ObjectId_var addr_srv_oid =
      poa->activate_object(&addr_srv_impl);
    tmpobj =
      poa->id_to_reference(addr_srv_oid.in());

    RtecUDPAdmin::AddrServer_var addr_srv =
      RtecUDPAdmin::AddrServer::_narrow(tmpobj.in());

    // Create and initialize the sender object
    PortableServer::Servant_var<TAO_ECG_UDP_Sender> sender =
                                TAO_ECG_UDP_Sender::create();
    TAO_ECG_UDP_Out_Endpoint endpoint;
    // need to be explicit about the address type when built with
    // IPv6 support, otherwise SOCK_DGram::open defaults to ipv6 when
    // given a sap_any address. This causes trouble on at least solaris
    // and windows, or at most on not-linux.
    if (endpoint.dgram ().open (ACE_Addr::sap_any,
                                send_addr.get_type()) == -1)
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot open send endpoint\n"),
                          1);
      }

   // TAO_ECG_UDP_Sender::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the sender will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    sender->init (ec.in (), addr_srv.in (), clone);

    // Setup the subscription and connect to the EC
    ACE_ConsumerQOS_Factory cons_qos_fact;
    cons_qos_fact.start_disjunction_group ();
    cons_qos_fact.insert (ACE_ES_EVENT_SOURCE_ANY, ACE_ES_EVENT_ANY, 0);
    RtecEventChannelAdmin::ConsumerQOS sub = cons_qos_fact.get_ConsumerQOS ();
    sender->connect (sub);

    // Create and initialize the receiver
    PortableServer::Servant_var<TAO_ECG_UDP_Receiver> receiver =
                                      TAO_ECG_UDP_Receiver::create();

    // TAO_ECG_UDP_Receiver::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the receiver will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone2 (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    receiver->init (ec.in (), clone2, addr_srv.in ());

    // Setup the registration and connect to the event channel
    ACE_SupplierQOS_Factory supp_qos_fact;
    supp_qos_fact.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    RtecEventChannelAdmin::SupplierQOS pub = supp_qos_fact.get_SupplierQOS ();
    receiver->connect (pub);

    // Create the appropriate event handler and register it with the reactor
    auto_ptr<ACE_Event_Handler> eh;
    if (mcast) {
      auto_ptr<TAO_ECG_Mcast_EH> mcast_eh(new TAO_ECG_Mcast_EH (receiver.in()));
      mcast_eh->reactor (orb->orb_core ()->reactor ());
      mcast_eh->open (ec.in());
      ACE_auto_ptr_reset(eh,mcast_eh.release());
      //eh.reset(mcast_eh.release());
    } else {
      auto_ptr<TAO_ECG_UDP_EH> udp_eh (new TAO_ECG_UDP_EH (receiver.in()));
      udp_eh->reactor (orb->orb_core ()->reactor ());
      ACE_INET_Addr local_addr (listenport);
      if (udp_eh->open (local_addr) == -1)
        ACE_ERROR ((LM_ERROR,"Cannot open EH\n"));

      ACE_auto_ptr_reset(eh,udp_eh.release());
      //eh.reset(udp_eh.release());
    }

    // Create an event (just a string in this case).

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);

    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;

#if !defined (TAO_LACKS_EVENT_CHANNEL_ANY)
    // Initialize data fields in event.
    const CORBA::String_var eventData =
      CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    event[0].data.any_value <<= eventData;
#else
    // Use the octet sequence payload instead
    char *tmpstr = const_cast<char *>(ACE_TEXT_ALWAYS_CHAR (ecname));
    size_t len = ACE_OS::strlen(tmpstr) +1;
    event[0].data.payload.replace (
      len,
      len,
      reinterpret_cast<CORBA::Octet *> (tmpstr));
#endif  /* !TAO_LACKS_EVENT_CHANNEL_ANY */

    if (iorfile != 0) {
      CORBA::String_var str = orb->object_to_string( ec.in() );
      std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
      iorFile << str.in() << std::endl;
      iorFile.close();
    }
    ACE_DEBUG ((LM_DEBUG,
    "Starting main loop\n"));

    const int EVENT_DELAY_MS = 1000;

    while (1) {
      consumer->push (event);

      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);
    }

    orb->destroy();
    return 0;
  }
  catch (const CORBA::Exception& exc)
  {
    ACE_ERROR ((LM_ERROR,
    "Caught CORBA::Exception\n%C (%C)\n",
    exc._name (),
    exc._rep_id () ));
  }
  return 1;
}
Ejemplo n.º 22
0
void
Job_i::work (CORBA::ULong work,
       CORBA::Short importance)
{
  static CORBA::ULong prime_number = 9619;

  if (TAO_debug_level > 0)
    ACE_DEBUG ((LM_DEBUG,
    "Job_i::work: %d units of work\n",
    work));

  CORBA::Object_var object =
    this->dt_creator_->orb ()->resolve_initial_references (
                                         "RTScheduler_Current");

  RTScheduling::Current_var current =
    RTScheduling::Current::_narrow (object.in ());
  RTScheduling::Current::IdType_var guid = current->id ();

  if (guid_ == 0)
    ACE_OS::memcpy (&guid_,
                    guid->get_buffer (),
                    sizeof (guid->length ()));

  if (TAO_debug_level > 0)
    ACE_DEBUG ((LM_DEBUG,
    "%t Guid is %d, Importance is %d\n",
    guid_,
    importance));

  ACE_TCHAR msg [BUFSIZ];
  ACE_OS::sprintf (msg,
                   ACE_TEXT("Guid is ")
                   ACE_SIZE_T_FORMAT_SPECIFIER
                   ACE_TEXT("\n"), guid_);

  dt_creator_->log_msg (ACE_TEXT_ALWAYS_CHAR(msg));

  for (; work != 0; work--)
    {
      //    ACE_hrtime_t now = ACE_OS::gethrtime ();

      ACE_Time_Value *base_time = dt_creator_->base_time ();
      if (base_time == 0)
        return;

      ACE_Time_Value run_time = ACE_OS::gettimeofday () - *(base_time);
      TASK_STATS::instance ()->sample (run_time.sec (), guid_);

      ACE_Time_Value count_down_time (1);
      ACE_Countdown_Time count_down (&count_down_time);

      while (count_down_time > ACE_Time_Value::zero)
        {
          ACE::is_prime (prime_number,
            2,
            prime_number / 2);
          count_down.update ();
        }

      run_time = ACE_OS::gettimeofday () - *(dt_creator_->base_time ());
      TASK_STATS::instance ()->sample (run_time.sec (), guid_);

      CORBA::Policy_var sched_param;
      sched_param = dt_creator_->sched_param (importance);
      const char * name = 0;
      current->update_scheduling_segment (name,
                sched_param.in (),
                sched_param.in ());
    }
}
Ejemplo n.º 23
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR *ecname = ACE_TEXT ("EventService");
    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          ecname = argv[i+1];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
    }

    // Find the Naming Service.
    CORBA::Object_var obj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context
      = CosNaming::NamingContextExt::_narrow(obj.in());

    // Find the EchoEventChannel.
    obj = root_context->resolve_str (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Downcast the object reference to an EventChannel reference.
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(obj.in());
    if (CORBA::is_nil(ec.in())) {
      std::cerr << "Could not narrow EchoEventChannel." << std::endl;
      return 1;
    }
    std::cout << "EchoEventConsumerMain.cpp: Found the EchoEventChannel." << std::endl;

    // Obtain a reference to the consumer administration object.
    RtecEventChannelAdmin::ConsumerAdmin_var admin = ec->for_consumers();

    // Obtain a reference to the push supplier proxy.
    RtecEventChannelAdmin::ProxyPushSupplier_var supplier =
      admin->obtain_push_supplier();

    // Get the RootPOA.
    obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Instantiate an EchoEventConsumer_i servant and register it
    // with the RootPOA
    PortableServer::Servant_var<EchoEventConsumer_i> servant =
      new EchoEventConsumer_i(orb.in(), supplier.in(), EVENT_LIMIT);
    PortableServer::ObjectId_var oid = poa->activate_object(servant.in());
    CORBA::Object_var consumer_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushConsumer_var consumer =
      RtecEventComm::PushConsumer::_narrow(consumer_obj.in());

    // Connect as a consumer.
    ACE_ConsumerQOS_Factory qos;
    qos.start_disjunction_group ();
    qos.insert (MY_SOURCE_ID,   // Source ID
                MY_EVENT_TYPE,  // Event Type
                0);             // handle to the rt_info
    supplier->connect_push_consumer (consumer.in (),
                                     qos.get_ConsumerQOS ());

    // Activate the POA via its POAManager.
    PortableServer::POAManager_var poa_manager = poa->the_POAManager();
    poa_manager->activate();

    std::cout << "EchoEventConsumerMain.cpp: Ready to receive events..." << std::endl;

    // Enter the ORB event loop.
    orb->run();

    // If we have reached this, we must be shutting down...
    // Disconnect the ProxyPushSupplier.
    orb->destroy();

    std::cout << "Test completed." << std::endl;

    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }
  return 1;
}
Ejemplo n.º 24
0
void
Handle_XMLUnion::handleData(const std::string& memberTypes_in)
{
  ACE_TRACE(ACE_TEXT("Handle_XMLUnion::handleData"));

  // step1: put all types into a list
  std::string current_type;
  std::string::size_type last_position = -1;
  std::string::size_type current_position = std::string::npos;
  for (current_position = memberTypes_in.find(ACE_TEXT_ALWAYS_CHAR(" "),
                                              last_position + 1);
       current_position != std::string::npos;
       current_position = memberTypes_in.find(ACE_TEXT_ALWAYS_CHAR(" "),
                                              last_position + 1))
  {
    current_type =
        memberTypes_in.substr(last_position + 1,
                              current_position - (last_position + 1));

    // strip leading namespace, if any
    std::string::size_type colon = current_type.find(ACE_TEXT_ALWAYS_CHAR(":"),
                                                     0);
    if (colon != std::string::npos)
      current_type = current_type.substr(colon + 1, std::string::npos);

    if (!myTypePostfix.empty())
    { // strip trailing "_Type", if any
      std::string::size_type type_position =
          current_type.rfind(myTypePostfix,
                             std::string::npos);
      if (type_position != std::string::npos)
        current_type.erase(type_position, std::string::npos);
    } // end IF

    myTypeList.push_back(current_type);

    // move forward
    last_position = current_position;
  } // end FOR
  current_type = memberTypes_in.substr(last_position + 1,
                                       current_position - (last_position + 1));

  // strip leading namespace, if any
  std::string::size_type colon = current_type.find(ACE_TEXT_ALWAYS_CHAR(":"), 0);
  if (colon != std::string::npos)
  {
    current_type = current_type.substr(colon + 1, std::string::npos);
  } // end IF

  if (!myTypePostfix.empty())
  { // strip trailing "_Type", if any
    std::string::size_type type_position = current_type.rfind(myTypePostfix,
                                                              std::string::npos);
    if (type_position != std::string::npos)
      current_type.erase(type_position, std::string::npos);
  } // end IF

  myTypeList.push_back(current_type);

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("union \"%s\" has %d items\n"),
             ACE_TEXT(myUnionName.c_str()),
             myTypeList.size()));

  // step2: emit types (generate individual identifiers...)
  bool isBaseType = false;
  std::string current_identifier;
  for (std::vector<std::string>::const_iterator iterator = myTypeList.begin();
       iterator != myTypeList.end();
       iterator++)
  {
    // convert basetypes XML --> C++
    isBaseType =
        XML2CppCode_Common_Tools::XMLintegratedtypeToString(*iterator,
                                                            current_type);

    // create identifier
    current_identifier = current_type;

    if (isBaseType)
    {
      // step1: remove any whitespaces...
      std::string::size_type current_space = std::string::npos;
      while ((current_space = current_identifier.find(' ',
                                                      0)) != std::string::npos)
        current_identifier.erase(current_space, 1);
    } // end IF
    else
    {
      // step1: remove any prefix...
      if (!myTypePrefix.empty())
      {
        std::string::size_type prefix = current_identifier.find(myTypePrefix, 0);
        if (prefix == 0)
          current_identifier = current_identifier.substr(myTypePrefix.size(),
                                                         std::string::npos);
      } // end IF

      // *TODO*:
      // the above works, but for foreign types, this gets messy...
      // just remove any data BEFORE the LAST "_", assuming this will kill excess data...
      std::string::size_type last_underscore =
          current_identifier.find_last_of(ACE_TEXT_ALWAYS_CHAR("_"),
                                          std::string::npos);
      if (last_underscore != std::string::npos)
        current_identifier = current_identifier.substr(last_underscore + 1,
                                                       std::string::npos);
    } // end ELSE

    // step2: transform to lowercase
    std::transform(current_identifier.begin(),
                   current_identifier.end(),
                   current_identifier.begin(),
                   std::bind2nd(std::ptr_fun(&std::tolower<char>),
                                std::locale("")));

    // OK: emit the line of code
    myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ");
    if (myEmitTaggedUnion)
      myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ");
    myOutputFile << current_type
                 << ACE_TEXT_ALWAYS_CHAR(" ")
                 << current_identifier
                 << ACE_TEXT_ALWAYS_CHAR(";")
                 << std::endl;
  } // end FOR
}
Ejemplo n.º 25
0
int
ECMS_Driver::parse_args (int argc, ACE_TCHAR *argv [])
{
  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("ds:n:t:h:p:b:"));
  int opt;

  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
        case 's':
          this->n_suppliers_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 'n':
          this->event_count_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 't':
          this->event_period_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 'b':
          this->event_size_ = ACE_OS::atoi (get_opt.opt_arg ());
          break;

        case 'h':
          {
            char* aux;
                char* arg = ACE_OS::strtok_r (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()), ",", &aux);

            this->event_a_ = ACE_ES_EVENT_UNDEFINED + ACE_OS::atoi (arg);
                arg = ACE_OS::strtok_r (0, ",", &aux);
            this->event_b_ = ACE_ES_EVENT_UNDEFINED + ACE_OS::atoi (arg);
          }
          break;

        case 'p':
          this->pid_file_name_ = get_opt.opt_arg ();
          break;

        case '?':
        default:
          ACE_DEBUG ((LM_DEBUG,
                      "Usage: %s "
                      "[ORB options] "
                      "-s <nsuppliers> "
                      "-n <event count> "
                      "-t <event period (usecs)> "
                      "-h <eventa,eventb> "
                      "-p <pid file name> "
                      "\n",
                      argv[0]));
          return -1;
        }
    }

  if (this->event_count_ <= 0)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "%s: event count (%d) is out of range, "
                  "reset to default (%d)\n",
                  argv[0], this->event_count_,
                  100));
      this->event_count_ = 100;
    }

  if (this->event_size_ < 0)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "%s: event size (%d) is out of range, "
                  "reset to default (%d)\n",
                  argv[0], this->event_size_,
                  32));
      this->event_count_ = 32;
    }

  if (this->n_suppliers_ <= 0)
    {
      this->n_suppliers_ = 1;
      ACE_ERROR_RETURN ((LM_ERROR,
                         "%s: number of suppliers out of range, "
                         "reset to default (%d)\n",
                         argv[0], 1), -1);
    }

  return 0;
}
Ejemplo n.º 26
0
void
Handle_XMLUnion::endElement()
{
  ACE_TRACE(ACE_TEXT("Handle_XMLUnion::endElement"));

  if (myEmitTaggedUnion)
  {
    // close union declaration
    myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("};") << std::endl
                 << std::endl;

    // emit discriminator enum type declaration
    std::string discriminator_typename = ACE_TEXT_ALWAYS_CHAR("Discriminator_t");
    myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("enum ")
                 << discriminator_typename
                 << std::endl
                 << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("{")
                 << std::endl;

    // emit types (generate individual identifiers...)
    // *TODO*: ensure no two element types are equal...
    bool isBaseType = false;
    std::string current_identifier;
    for (std::vector<std::string>::const_iterator iterator = myTypeList.begin();
         iterator != myTypeList.end();
         iterator++)
    {
      // convert basetypes XML --> C++
      isBaseType =
          XML2CppCode_Common_Tools::XMLintegratedtypeToString(*iterator,
                                                              current_identifier);
      if (isBaseType)
      {
        // step1: remove any whitespaces...
        std::string::size_type current_space = std::string::npos;
        while ((current_space = current_identifier.find(' ',
                                                        0)) != std::string::npos)
          current_identifier.erase(current_space, 1);
      } // end IF
      else
      {
        // step1: remove any prefix...
        if (!myTypePrefix.empty())
        {
          std::string::size_type prefix = current_identifier.find(myTypePrefix,
                                                                  0);
          if (prefix == 0)
            current_identifier = current_identifier.substr(myTypePrefix.size(),
                                                           std::string::npos);
        } // end IF

        // *TODO*:
        // the above works, but for foreign types, this gets messy...
        // just remove any data BEFORE the LAST "_", assuming this will kill excess data...
        std::string::size_type last_underscore =
            current_identifier.find_last_of(ACE_TEXT_ALWAYS_CHAR("_"),
                                            std::string::npos);
        if (last_underscore != std::string::npos)
          current_identifier = current_identifier.substr(last_underscore + 1,
                                                         std::string::npos);
      } // end ELSE

      // step2: transform to uppercase
      std::transform(current_identifier.begin(),
                     current_identifier.end(),
                     current_identifier.begin(),
                     std::bind2nd(std::ptr_fun(&std::toupper<char>),
                                  std::locale("")));

      // *PORTABILITY*: "DOMAIN" seems to be a constant (see math.h)
      // --> provide a (temporary) workaround here...
#if defined __GNUC__ || defined _MSC_VER
#pragma message("applying quirk code for this compiler...")
      if (current_identifier == ACE_TEXT_ALWAYS_CHAR("DOMAIN"))
        current_identifier.insert(0, ACE_TEXT_ALWAYS_CHAR("__QUIRK__"));
#else
#pragma error("re-check code for this compiler")
#endif

      // OK: emit the line of code
      myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                   << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                   << current_identifier;
//       if ((iterator + 1) != myTypeList.end())
      myOutputFile << ACE_TEXT_ALWAYS_CHAR(",");
      myOutputFile << std::endl;
    } // end FOR

    myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("INVALID") << std::endl
                 << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("};") << std::endl
                 << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << discriminator_typename
                 << ACE_TEXT_ALWAYS_CHAR(" discriminator;") << std::endl;
  } // end IF

  myOutputFile << ACE_TEXT_ALWAYS_CHAR("};")
               << std::endl;
  myOutputFile << std::endl;
}
Ejemplo n.º 27
0
void
Handle_XMLUnion::startElement(const std::string& union_in)
{
  ACE_TRACE(ACE_TEXT("Handle_XMLUnion::startElement"));

  myUnionName = union_in;

  if (!myEmitClassQualifier.empty())
  {
	std::string exports_filename = myTypePrefix;
	exports_filename += ACE_TEXT_ALWAYS_CHAR("_");
	exports_filename += ACE_TEXT_ALWAYS_CHAR(XML2CPPCODE_DLL_EXPORT_INCLUDE_SUFFIX);
	exports_filename += ACE_TEXT_ALWAYS_CHAR(XML2CPPCODE_HEADER_EXTENSION);
	// transform to lowercase
	std::transform(exports_filename.begin(),
                   exports_filename.end(),
                   exports_filename.begin(),
                   std::bind2nd(std::ptr_fun(&std::tolower<char>),
                                std::locale("")));

	myOutputFile << ACE_TEXT_ALWAYS_CHAR("#include \"");
	myOutputFile << exports_filename.c_str();
	myOutputFile << ACE_TEXT_ALWAYS_CHAR("\"") << std::endl << std::endl;
  } // end IF

  if (myEmitTaggedUnion)
  {
    std::string::size_type current_position = std::string::npos;
    std::string taggedunion_typename = myUnionName;
    current_position =
        taggedunion_typename.rfind(ACE_TEXT_ALWAYS_CHAR(XML2CPPCODE_DEFAULTUNIONPOSTFIX),
                                   std::string::npos);
    ACE_ASSERT(current_position != std::string::npos);
//     taggedunion_typename.insert(current_position, ACE_TEXT_ALWAYS_CHAR(XML2CPPCODE_DEFAULTTAGGEDUNIONINFIX));
    myOutputFile << ACE_TEXT_ALWAYS_CHAR("struct ");
	if (!myEmitClassQualifier.empty())
	{
	  myOutputFile << myEmitClassQualifier.c_str();
	  myOutputFile << ACE_TEXT_ALWAYS_CHAR(" ");
	} // end IF
	myOutputFile << taggedunion_typename
                 << std::endl
                 << ACE_TEXT_ALWAYS_CHAR("{")
                 << std::endl
                 << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ")
                 << ACE_TEXT_ALWAYS_CHAR("union")
                 << std::endl;
  } // end IF
  else
  {
    myOutputFile << ACE_TEXT_ALWAYS_CHAR("union ")
                 << myUnionName
                 << std::endl;
  } // end ELSE

  if (myEmitTaggedUnion)
    myOutputFile << std::setw(XML2CPPCODE_INDENT) << ACE_TEXT_ALWAYS_CHAR(" ");
  myOutputFile << ACE_TEXT_ALWAYS_CHAR("{")
               << std::endl;
}
Ejemplo n.º 28
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
    try {
        // Initialize the ORB.
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

        // Create a MessengerServer object.
        MessengerServer * server = new MessengerServer (orb.in());
        ACE_Auto_Ptr<MessengerServer> safe_ptr (server);

        // Parse arguments to determine how we should shutdown.
        if (server->parse_args (argc, argv) != 0)
            return 1;

        //Get reference to the RootPOA.
        CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
        PortableServer::POA_var poa = PortableServer::POA::_narrow( obj.in() );

        // Activate the POAManager.
        PortableServer::POAManager_var mgr = poa->the_POAManager();
        mgr->activate();

        // Create a servant.
        Messenger_i messenger_servant (orb.in());

        // Register the servant with the RootPOA, obtain its object
        // reference, stringify it, and write it to a file.
        PortableServer::ObjectId_var oid =
            poa->activate_object( &messenger_servant );
        CORBA::Object_var messenger_obj = poa->id_to_reference( oid.in() );
        CORBA::String_var str = orb->object_to_string( messenger_obj.in() );
        std::ofstream iorFile(ACE_TEXT_ALWAYS_CHAR (ior_output_file.c_str ()));
        iorFile << str.in() << std::endl;
        iorFile.close();
        std::cout << "IOR written to file " <<
                  ACE_TEXT_ALWAYS_CHAR (ior_output_file.c_str ()) << std::endl;

        switch (s_method)
        {
        // shutdown on client invocation
        case MessengerServer::s_client_call:
            std::cout << "Will shutdown on client invocation." << std::endl;
            server->run ();
            break;

        // shutdown after some iterations through loop
        case MessengerServer::s_polling_loop:
            server->poll (loop_iterations);
            break;

        // schedule a timer to shutdown
        case MessengerServer::s_timer:
            server->schedule_shutdown_timer (timeout);
            server->run ();
            break;

        // shutdown on console input
        case MessengerServer::s_console_input:
            server->shutdown_on_console_input ();
            server->run ();
            break;

        // use CORBA::ORB::run() with time value
        case MessengerServer::s_run_time_value:
            server->run (timeout);
            break;
        }
    }
    catch(const CORBA::Exception& ex) {
        std::cerr << "CORBA exception: " << ex << std::endl;
        return 1;
    }

    return 0;
}
Ejemplo n.º 29
0
int
TAO::HTIOP::Protocol_Factory::init (int argc,
                                  ACE_TCHAR* argv[])
{
  const ACE_TCHAR * config_file = 0;
  const ACE_TCHAR * persist_file = 0;
  unsigned proxy_port = 0;
  const ACE_TCHAR * proxy_host = 0;

  ACE_stat statbuf;
  int use_registry = 0;

  for (int i = 0; i < argc; i++)
    {
      if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-config")) == 0)
        {
          if (++i < argc)
            if (ACE_OS::stat (argv[i],&statbuf) != -1)
              config_file = argv[i];
        }
      else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-env_persist")) == 0)
        {
          if (++i < argc)
            if (ACE_OS::stat (argv[i],&statbuf) != -1)
              persist_file = argv[i];
        }
      else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-win32_reg")) == 0)
        {
          use_registry = 1;
        }
      else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-inside")) == 0)
        {
          if (++i < argc)
            this->inside_ = ACE_OS::atoi (ACE_TEXT_ALWAYS_CHAR(argv[i]));
        }
      else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-proxy_port")) == 0)
        {
          if (++i < argc)
            proxy_port = static_cast<unsigned>
              (ACE_OS::atoi (ACE_TEXT_ALWAYS_CHAR(argv[i])));
        }
      else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT("-proxy_host")) == 0)
        {
          if (++i < argc)
            if (ACE_OS::stat (argv[i],&statbuf) != -1)
              proxy_host = argv[i];
        }
    }

  ACE_NEW_RETURN (this->ht_env_,
                  ACE::HTBP::Environment(0,
                                       use_registry,
                                       persist_file),
                  -1);

  if (config_file != 0)
    this->ht_env_->import_config (config_file);
  else
    {
      if (proxy_port != 0)
        this->ht_env_->set_proxy_port (proxy_port);
      if (proxy_host != 0)
        this->ht_env_->set_proxy_host (proxy_host);
    }
  return 0;
}
Ejemplo n.º 30
0
int
TAO_Naming_Server::init_with_orb (int argc,
                                  ACE_TCHAR *argv [],
                                  CORBA::ORB_ptr orb)
{
  int result;

  try
    {
      // Duplicate the ORB
      this->orb_ = CORBA::ORB::_duplicate (orb);

      // Get the POA from the ORB.
      CORBA::Object_var poa_object =
        orb->resolve_initial_references ("RootPOA");

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

      // Check the non-ORB arguments.  this needs to come before we
      // initialize my_naming_server so that we can pass on some of
      // the command-line arguments.
      result = this->parse_args (argc, argv);

      if (result < 0)
        return result;

      // Get the POA object.
      this->root_poa_ = PortableServer::POA::_narrow (poa_object.in ());

      // Get the POA_Manager.
      PortableServer::POAManager_var poa_manager =
        this->root_poa_->the_POAManager ();

#if defined (CORBA_E_MICRO)
      this->ns_poa_ = PortableServer::POA::_duplicate (this->root_poa_);
#else
      int numPolicies = 2;
# if (TAO_HAS_MINIMUM_POA == 0)
      if (this->use_storable_context_)
        {
          this->use_servant_activator_ = true;
        }

      if (this->use_servant_activator_) {
        numPolicies += 2;
      }
# endif /* TAO_HAS_MINIMUM_POA */

      CORBA::PolicyList policies (numPolicies);
      policies.length (numPolicies);

      // Id Assignment policy
      policies[0] =
        this->root_poa_->create_id_assignment_policy (PortableServer::USER_ID);

      // Lifespan policy
      policies[1] =
        this->root_poa_->create_lifespan_policy (PortableServer::PERSISTENT);

# if (TAO_HAS_MINIMUM_POA == 0) && !defined (CORBA_E_COMPACT)
      if (this->use_servant_activator_)
        {
          // Request Processing Policy
          policies[2] =
            this->root_poa_->create_request_processing_policy (PortableServer::USE_SERVANT_MANAGER);

          // Servant Retention Policy
          policies[3] =
            this->root_poa_->create_servant_retention_policy (PortableServer::RETAIN);
        }
# endif /* TAO_HAS_MINIMUM_POA */

      // We use a different POA, otherwise the user would have to change
      // the object key each time it invokes the server.
      this->ns_poa_ = this->root_poa_->create_POA ("NameService",
                                                   poa_manager.in (),
                                                   policies);
      // Warning!  If create_POA fails, then the policies won't be
      // destroyed and there will be hell to pay in memory leaks!

      // Creation of the new POAs over, so destroy the Policy_ptr's.
      for (CORBA::ULong i = 0;
           i < policies.length ();
           ++i)
        {
          CORBA::Policy_ptr policy = policies[i];
          policy->destroy ();
        }
#endif /* CORBA_E_MICRO */

      poa_manager->activate ();

#if defined (CORBA_E_MICRO)
      result = this->init (orb,
                           this->ns_poa_.in (),
                           this->context_size_,
                           0,
                           0,
                           0,
                           0,
                           this->multicast_,
                           false,
                           this->round_trip_timeout_,
                           this->use_round_trip_timeout_);
#else
      result = this->init (orb,
                           this->ns_poa_.in (),
                           this->context_size_,
                           0,
                           0,
                           this->persistence_file_name_,
                           this->base_address_,
                           this->multicast_,
                           this->use_storable_context_,
                           this->round_trip_timeout_,
                           this->use_round_trip_timeout_);
#endif /* CORBA_E_MICRO */

      if (result == -1)
        return result;
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception (
        "TAO_Naming_Server::init_with_orb");
      return -1;
    }

  // If an ior file name was provided on command line
  if (this->ior_file_name_ != 0)
    {
      CORBA::String_var ns_ior = this->naming_service_ior ();
      if (this->write_ior_to_file (
            ns_ior.in (),
            ACE_TEXT_ALWAYS_CHAR (this->ior_file_name_)) != 0)
        {
          ORBSVCS_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT("Unable to open %C for writing:(%u) %p\n"),
                             this->ior_file_name_,
                             ACE_ERRNO_GET,
                             ACE_TEXT("TAO_Naming_Server::init_with_orb")),
                            -1);
        }
    }

  if (this->pid_file_name_ != 0)
    {
      FILE *pidf = ACE_OS::fopen (this->pid_file_name_, ACE_TEXT("w"));
      if (pidf != 0)
        {
          ACE_OS::fprintf (pidf,
                           "%ld\n",
                           static_cast<long> (ACE_OS::getpid ()));
          ACE_OS::fclose (pidf);
        }
    }

  return 0;
}