Example #1
0
int
be_visitor_interface_ss::gen_abstract_ops_helper (
  be_interface *node,
  be_interface *base,
  TAO_OutStream *os)
{
  if (!base->is_abstract ())
    {
      return 0;
    }

  AST_Decl *d = 0;
  be_visitor_context ctx;
  ctx.stream (os);
  ctx.state (TAO_CodeGen::TAO_ROOT_SS);

  for (UTL_ScopeActiveIterator si (base, UTL_Scope::IK_decls);
       !si.is_done ();
       si.next ())
    {
      d = si.item ();

      if (d == 0)
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("be_visitor_interface_ss::")
                             ACE_TEXT ("gen_abstract_ops_helper - ")
                             ACE_TEXT ("bad node in this scope\n")),
                            -1);
        }

      AST_Decl::NodeType nt = d->node_type ();

      UTL_ScopedName *item_new_name = 0;
      UTL_ScopedName *new_name = 0;

      if (AST_Decl::NT_op == nt || AST_Decl::NT_attr == nt)
        {
          ACE_NEW_RETURN (item_new_name,
                          UTL_ScopedName (d->local_name ()->copy (),
                                          0),
                          -1);

          new_name = (UTL_ScopedName *) node->name ()->copy ();
          new_name->nconc (item_new_name);
        }
      else
        {
          continue;
        }

      // We pass the node's is_abstract flag to the operation
      // constructor so we will get the right generated operation
      // body if we are regenerating an operation from an
      // abstract interface in a concrete interface or component.
      if (AST_Decl::NT_op == nt)
        {
          be_operation *op = be_operation::narrow_from_decl (d);
          UTL_ScopedName *old_name =
            (UTL_ScopedName *) op->name ()->copy ();
          op->set_name (new_name);
          op->set_defined_in (node);
          op->is_abstract (node->is_abstract ());

          be_visitor_operation_ss op_visitor (&ctx);
          op_visitor.visit_operation (op);

          op->set_name (old_name);
          op->set_defined_in (base);
          op->is_abstract (base->is_abstract ());
        }
      else if (AST_Decl::NT_attr == nt)
        {
          AST_Attribute *attr =
            AST_Attribute::narrow_from_decl (d);
          be_attribute new_attr (attr->readonly (),
                                 attr->field_type (),
                                 0,
                                 attr->is_local (),
                                 attr->is_abstract ());
          new_attr.set_defined_in (node);
          new_attr.set_name (new_name);

          UTL_ExceptList *get_exceptions =
            attr->get_get_exceptions ();

          if (0 != get_exceptions)
            {
              new_attr.be_add_get_exceptions (get_exceptions->copy ());
            }

          UTL_ExceptList *set_exceptions =
            attr->get_set_exceptions ();

          if (0 != set_exceptions)
            {
              new_attr.be_add_set_exceptions (set_exceptions->copy ());
            }

          be_visitor_attribute attr_visitor (&ctx);
          attr_visitor.visit_attribute (&new_attr);
          ctx.attribute (0);
          new_attr.destroy ();
        }
    }

  return 0;
}
Example #2
0
ACE_Message_Block *
ACE_Message_Block::clone (Message_Flags mask) const
{
  ACE_TRACE ("ACE_Message_Block::clone");

  // Get a pointer to a "cloned" <ACE_Data_Block> (will copy the
  // values rather than increment the reference count).
  ACE_Data_Block *db = this->data_block ()->clone (mask);

  if (db == 0)
    return 0;

  ACE_Message_Block *nb = 0;

  if(message_block_allocator_ == 0)
    {
      ACE_NEW_RETURN (nb,
                      ACE_Message_Block (0, // size
                                         ACE_Message_Type (0), // type
                                         0, // cont
                                         0, // data
                                         0, // allocator
                                         0, // locking strategy
                                         0, // flags
                                         this->priority_, // priority
                                         ACE_EXECUTION_TIME, // execution time
                                         ACE_DEADLINE_TIME, // absolute time to deadline
                                         // Get a pointer to a
                                         // "duplicated" <ACE_Data_Block>
                                         // (will simply increment the
                                         // reference count).
                                         db,
                                         db->data_block_allocator (),
                                         this->message_block_allocator_),
                      0);
    }
  else
    {
      // This is the ACE_NEW_MALLOC macro with the return check removed.
      // We need to do it this way because if it fails we need to release
      // the cloned data block that was created above.  If we used
      // ACE_NEW_MALLOC_RETURN, there would be a memory leak because the
      // above db pointer would be left dangling.
      nb = static_cast<ACE_Message_Block*> (message_block_allocator_->malloc (sizeof (ACE_Message_Block)));
      if(nb != 0)
        new (nb) ACE_Message_Block (0, // size
                                    ACE_Message_Type (0), // type
                                    0, // cont
                                    0, // data
                                    0, // allocator
                                    0, // locking strategy
                                    0, // flags
                                    this->priority_, // priority
                                    ACE_EXECUTION_TIME, // execution time
                                    ACE_DEADLINE_TIME, // absolute time to deadline
                                    db,
                                    db->data_block_allocator (),
                                    this->message_block_allocator_);
    }

  if (nb == 0)
    {
      db->release ();
      return 0;
    }

  // Set the read and write pointers in the new <Message_Block> to the
  // same relative offset as in the existing <Message_Block>.
  nb->rd_ptr (this->rd_ptr_);
  nb->wr_ptr (this->wr_ptr_);

  // Clone all the continuation messages if necessary.
  if (this->cont () != 0
      && (nb->cont_ = this->cont ()->clone (mask)) == 0)
    {
      nb->release ();
      return 0;
    }
  return nb;
}
Example #3
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  ACE_LOG_MSG->open (argv[0] ? argv[0] : ACE_TEXT("preempt"));

#if defined (ACE_HAS_THREADS) || !defined (ACE_LACKS_FORK)

  u_int i;

  if (get_options (argc, argv))
    ACE_OS::exit (-1);

  // Enable FIFO scheduling, e.g., RT scheduling class on Solaris.
  if (ACE_OS::sched_params (
        ACE_Sched_Params (
          ACE_SCHED_FIFO,
          ACE_Sched_Params::priority_min (ACE_SCHED_FIFO),
          ACE_SCOPE_PROCESS)) != 0)
    {
      if (ACE_OS::last_error () == EPERM)
        ACE_DEBUG ((LM_MAX, "preempt: user is not superuser, "
                    "so remain in time-sharing class\n"));
      else
        ACE_ERROR_RETURN ((LM_ERROR, "%n: ACE_OS::sched_params failed\n%a"),
                          -1);
    }

  High_Priority_Task *high_priority_task;
  ACE_NEW_RETURN (high_priority_task, High_Priority_Task [high_priority_tasks],
                  1);

  Low_Priority_Task low_priority_task (high_priority_task[0]);

  if (! use_fork)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) main (), wait for threads to exit . . .\n"));
    }

  // Save the start time, so that deltas can be displayed later.
  starttime = ACE_OS::gethrtime ();

  // Spawn the threads/processes . . .
  pid_t child = 0;
  if (use_fork == 1)
    {
      switch ((child = ACE_OS::fork (ACE_TEXT("preempt-low_priority_process"))))
        {
        case -1:
          ACE_ERROR ((LM_ERROR, "%p\n%a", "fork failed"));
          return -1;
        case 0: // In child
          {
            low_priority_task.open (0);
            break;
          }
        default: // In parent
          for (i = 0; i < high_priority_tasks; ++i)
            {
              high_priority_task[i].open (0);
            }
          break;
        }
    }
  else
    {
      for (i = 0; i < high_priority_tasks; ++i)
        {
          high_priority_task[i].open (0);
        }
      low_priority_task.open (0);

#if defined (ACE_HAS_THREADS)
     // Wait for all threads to exit.
     ACE_Thread_Manager::instance ()->wait ();
#endif /* ACE_HAS_THREADS */
    }

  // Display the time deltas.  They should be about a half second apart.
  if (child || ! use_fork)
    {
      for (i = 0; i < high_priority_tasks; ++i)
        {
          ACE_DEBUG ((LM_DEBUG, "High priority task %u:\n", i + 1));
          high_priority_task[i].print_times ();
        }
    }

  delete [] high_priority_task;

#else  /* ! ACE_HAS_THREADS && ACE_LACKS_FORK */
  ACE_UNUSED_ARG (argc);
  ACE_UNUSED_ARG (argv);
  ACE_ERROR ((LM_ERROR, "threads and fork not supported on this platform\n"));
#endif /* ! ACE_HAS_THREADS && ACE_LACKS_FORK */

  return 0;
}
Example #4
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  CORBA::ORB_var orb;

  try
    {
      PortableInterceptor::ORBInitializer_ptr temp_orb_initializer =
        PortableInterceptor::ORBInitializer::_nil ();
      PortableInterceptor::ORBInitializer_var orb_initializer;

      // Register the ClientRequest_Interceptor ORBInitializer.
      ACE_NEW_RETURN (temp_orb_initializer,
                      ClientORBInitializer,
                      -1);

      orb_initializer = temp_orb_initializer;

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

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

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

      CORBA::Object_var tmp =
        orb->string_to_object (ior);

      Test::Hello_var hello =
        Test::Hello::_narrow(tmp.in () );

      if (CORBA::is_nil (hello.in ()))
        {
          ACE_ERROR_RETURN ((LM_DEBUG,
                             "Nil Test::Hello reference <%s>\n",
                             ior),
                            1);
        }

      ACE_DEBUG ((LM_DEBUG, "Client about to make method call that is doomed to failure...\n"));

      CORBA::String_var the_string =
        hello->get_string ();

      ACE_ERROR_RETURN ((LM_DEBUG,
                            "Error - the remote call succeeded which is bloody miraculous given that no server is running !!\n"),
                            1);

      orb->destroy ();
    }
  catch (const CORBA::Exception&)
    {
      orb->destroy ();

      if (ClientRequest_Interceptor::success_flag_)
        {
          ACE_DEBUG ((LM_DEBUG, "Success - the server was unreachable and PI receive_exception was invoked.\n"));
          return 0;
        }
      else
        {
          ACE_ERROR_RETURN ((LM_DEBUG,
                             "Error: regression failed - interceptor receive_exception interception point was not invoked !!\n"),
                            1);
        }
    }

  return 1;
}
Example #5
0
int
BE_init(int&, ACE_TCHAR*[])
{
    ACE_NEW_RETURN(be_global, BE_GlobalData, -1);
    return 0;
}
Example #6
0
int
Periodic_Task::init_task (ACE_Arg_Shifter& arg_shifter)
{
  const ACE_TCHAR *current_arg = 0;

  while (arg_shifter.is_anything_left ())
    {
      if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-JobName"))))
        {
          name_ = ACE_TEXT_ALWAYS_CHAR(current_arg);
          arg_shifter.consume_arg ();
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Priority"))))
        {
          task_priority_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Period"))))
        {
          period_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-ExecTime"))))
        {
          exec_time_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Phase"))))
        {
          phase_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Iter"))))
        {
          iter_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();

          // create the stat object.
          ACE_NEW_RETURN (task_stats_, Task_Stats (iter_), -1);

          if (task_stats_->init () == -1)
            return -1;
        }
      else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Load"))))
        {
          load_ = ACE_OS::atoi (current_arg);
          arg_shifter.consume_arg ();

          return 0;
        }
      else
        {
          ACE_DEBUG ((LM_DEBUG, "parse Task unknown option %s\n",
                      arg_shifter.get_current ()));
          if (TAO_debug_level > 0)
            ACE_DEBUG ((LM_DEBUG, "name %s, priority %d, period %duS, exec_time %duS, phase %duS, iter %d, load %d\n",
                        name_.c_str(), task_priority_, period_, exec_time_, phase_, iter_, load_));
          break;
        }
    }
  return 0;
}
Example #7
0
int WorldSocket::SendPacket(WorldPacket const& pct)
{
    ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);

    if (closing_)
        return -1;

    // Dump outgoing packet
    if (sPacketLog->CanLogPacket())
        sPacketLog->LogPacket(pct, SERVER_TO_CLIENT);

    WorldPacket const* pkt = &pct;

    // Empty buffer used in case packet should be compressed
    // Disable compression for now :)
   /* WorldPacket buff;
    if (m_Session && pkt->size() > 0x400)
    {
        buff.Compress(m_Session->GetCompressionStream(), pkt);
        pkt = &buff;
    }*/

    if (m_Session)
        TC_LOG_TRACE("network.opcode", "S->C: %s %s", m_Session->GetPlayerInfo().c_str(), GetOpcodeNameForLogging(pkt->GetOpcode()).c_str());

    sScriptMgr->OnPacketSend(this, *pkt);

    ServerPktHeader header(!m_Crypt.IsInitialized() ? pkt->size() + 2 : pct.size(), pkt->GetOpcode(), &m_Crypt);

    if (m_OutBuffer->space() >= pkt->size() + header.getHeaderLength() && msg_queue()->is_empty())
    {
        // Put the packet on the buffer.
        if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1)
            ACE_ASSERT (false);

        if (!pkt->empty())
            if (m_OutBuffer->copy((char*) pkt->contents(), pkt->size()) == -1)
                ACE_ASSERT (false);
    }
    else
    {
        // Enqueue the packet.
        ACE_Message_Block* mb;

        ACE_NEW_RETURN(mb, ACE_Message_Block(pkt->size() + header.getHeaderLength()), -1);

        mb->copy((char*) header.header, header.getHeaderLength());

        if (!pkt->empty())
            mb->copy((const char*)pkt->contents(), pkt->size());

        if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
        {
            TC_LOG_ERROR("network", "WorldSocket::SendPacket enqueue_tail failed");
            mb->release();
            return -1;
        }
    }

    return 0;
}
Example #8
0
File: Worker.cpp Project: SEDS/CUTS
//
// begin
//
CUTS_Action_Iterator * CUTS_Worker::begin (void)
{
  CUTS_Action_Iterator * iter = 0;
  ACE_NEW_RETURN (iter, CUTS_Action_Iterator (), 0);
  return iter;
}
Example #9
0
ACE_BEGIN_VERSIONED_NAMESPACE_DECL

int
ACE_OS::argv_to_string (ACE_TCHAR **argv,
                        ACE_TCHAR *&buf,
                        int substitute_env_args)
{
  if (argv == 0 || argv[0] == 0)
    return 0;

  size_t buf_len = 0;

  // Determine the length of the buffer.

  for (int i = 0; argv[i] != 0; i++)
    {
#if !defined (ACE_LACKS_ENV)
      // Account for environment variables.
      if (substitute_env_args && argv[i][0] == ACE_LIB_TEXT ('$'))
        {
#  if defined (ACE_WIN32) || !defined (ACE_HAS_WCHAR)
          ACE_TCHAR *temp = 0;
          // Win32 is the only platform with a wide-char ACE_OS::getenv().
          if ((temp = ACE_OS::getenv (&argv[i][1])) != 0)
            buf_len += ACE_OS::strlen (temp);
          else
            buf_len += ACE_OS::strlen (argv[i]);
#  else
          // This is an ACE_HAS_WCHAR platform and not ACE_WIN32.
          // Convert the env variable name for getenv(), then add
          // the length of the returned char *string. Later, when we
          // actually use the returned env variable value, convert it
          // as well.
          char *ctemp = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (&argv[i][1]));
          if (ctemp == 0)
            buf_len += ACE_OS::strlen (argv[i]);
          else
            buf_len += ACE_OS::strlen (ctemp);
#  endif /* ACE_WIN32 || !ACE_HAS_WCHAR */
        }
      else
#endif /* ACE_LACKS_ENV */
        buf_len += ACE_OS::strlen (argv[i]);

      // Add one for the extra space between each string.
      buf_len++;
    }

  // Step through all argv params and copy each one into buf; separate
  // each param with white space.

  ACE_NEW_RETURN (buf,
                  ACE_TCHAR[buf_len + 1],
                  0);

  // Initial null charater to make it a null string.
  buf[0] = '\0';
  ACE_TCHAR *end = buf;
  int j;

  for (j = 0; argv[j] != 0; j++)
    {

#if !defined (ACE_LACKS_ENV)
      // Account for environment variables.
      if (substitute_env_args && argv[j][0] == ACE_LIB_TEXT ('$'))
        {
#  if defined (ACE_WIN32) || !defined (ACE_HAS_WCHAR)
          // Win32 is the only platform with a wide-char ACE_OS::getenv().
          ACE_TCHAR *temp = ACE_OS::getenv (&argv[j][1]);
          if (temp != 0)
            end = ACE_OS::strecpy (end, temp);
          else
            end = ACE_OS::strecpy (end, argv[j]);
#  else
          // This is an ACE_HAS_WCHAR platform and not ACE_WIN32.
          // Convert the env variable name for getenv(), then convert
          // the returned char *string back to wchar_t.
          char *ctemp = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (&argv[j][1]));
          if (ctemp == 0)
            end = ACE_OS::strecpy (end, argv[j]);
          else
            end = ACE_OS::strecpy (end, ACE_TEXT_CHAR_TO_TCHAR (ctemp));
#  endif /* ACE_WIN32 || !ACE_HAS_WCHAR */
        }
      else
#endif /* ACE_LACKS_ENV */
        end = ACE_OS::strecpy (end, argv[j]);

      // Replace the null char that strecpy put there with white
      // space.
      end[-1] = ' ';
    }

  // Null terminate the string.
  *end = '\0';
  // The number of arguments.
  return j;
}
Example #10
0
template<class SVC_HANDLER, ACE_PEER_CONNECTOR_1, class MUTEX> int
ACE_Cached_Connect_Strategy<SVC_HANDLER, ACE_PEER_CONNECTOR_2, MUTEX>::open
(creation_strategy_type *cre_s,
 ACE_Concurrency_Strategy<SVC_HANDLER> *con_s,
 ACE_Recycling_Strategy<SVC_HANDLER> *rec_s)
{
  // Initialize the creation strategy.

  // First we decide if we need to clean up.
  if (this->creation_strategy_ != 0 &&
      this->delete_creation_strategy_ != 0 &&
      cre_s != 0)
    {
      delete this->creation_strategy_;
      this->creation_strategy_ = 0;
      this->delete_creation_strategy_ = 0;
    }

  if (cre_s != 0)
    this->creation_strategy_ = cre_s;
  else if (this->creation_strategy_ == 0)
    {
      ACE_NEW_RETURN (this->creation_strategy_,
                      CREATION_STRATEGY, -1);
      this->delete_creation_strategy_ = 1;
    }

  // Initialize the concurrency strategy.

  if (this->concurrency_strategy_ != 0 &&
      this->delete_concurrency_strategy_ != 0 &&
      con_s != 0)
    {
      delete this->concurrency_strategy_;
      this->concurrency_strategy_ = 0;
      this->delete_concurrency_strategy_ = 0;
    }

  if (con_s != 0)
    this->concurrency_strategy_ = con_s;
  else if (this->concurrency_strategy_ == 0)
    {
      ACE_NEW_RETURN (this->concurrency_strategy_,
                      CONCURRENCY_STRATEGY, -1);
      this->delete_concurrency_strategy_ = 1;
    }

  // Initialize the recycling strategy.

  if (this->recycling_strategy_ != 0 &&
      this->delete_recycling_strategy_ != 0 &&
      rec_s != 0)
    {
      delete this->recycling_strategy_;
      this->recycling_strategy_ = 0;
      this->delete_recycling_strategy_ = 0;
    }

  if (rec_s != 0)
    this->recycling_strategy_ = rec_s;
  else if (this->recycling_strategy_ == 0)
    {
      ACE_NEW_RETURN (this->recycling_strategy_,
                      RECYCLING_STRATEGY, -1);
      this->delete_recycling_strategy_ = 1;
    }

  return 0;
}
Example #11
0
TAO::CSD::Strategy_Base::DispatchResult
TAO_DTP_POA_Strategy::dispatch_collocated_request_i
                             (TAO_ServerRequest&              server_request,
                              const PortableServer::ObjectId& object_id,
                              PortableServer::POA_ptr         poa,
                              const char*                     operation,
                              PortableServer::Servant         servant)
{


  TAO::CSD::TP_Servant_State::HandleType servant_state =
                        this->get_servant_state (servant);

  bool is_sync_with_server = server_request.sync_with_server ();
  bool is_synchronous      = server_request.response_expected ();

  TAO::CSD::TP_Collocated_Synch_Request_Handle
    synch_request;
  TAO::CSD::TP_Collocated_Synch_With_Server_Request_Handle
    synch_with_server_request;
  TAO::CSD::TP_Request_Handle
    request;

  // Create the request object using the appropriate concrete type.
  if (is_sync_with_server)
    {
      TAO::CSD::TP_Collocated_Synch_With_Server_Request *req_ptr;
      ACE_NEW_RETURN (req_ptr,
                      TAO::CSD::TP_Collocated_Synch_With_Server_Request
                        (server_request,
                         object_id,
                         poa,
                         operation,
                         servant,
                         servant_state.in ()),
                      DISPATCH_REJECTED);

      synch_with_server_request = req_ptr;

      // Give the request handle its own "copy".
      synch_with_server_request->_add_ref ();
      request = synch_with_server_request.in ();
    }
  else if (is_synchronous)
    {

      TAO::CSD::TP_Collocated_Synch_Request *req_ptr;
      ACE_NEW_RETURN (req_ptr,
                      TAO::CSD::TP_Collocated_Synch_Request (
                                   server_request,
                                   object_id,
                                   poa,
                                   operation,
                                   servant,
                                   servant_state.in ()),
                      DISPATCH_REJECTED);

      synch_request = req_ptr;

      // Give the request handle its own "copy".
      synch_request->_add_ref ();
      request = synch_request.in ();
    }
  else
    {
      TAO::CSD::TP_Collocated_Asynch_Request *req_ptr;
      ACE_NEW_RETURN (req_ptr,
                      TAO::CSD::TP_Collocated_Asynch_Request (server_request,
                                                              object_id,
                                                              poa,
                                                              operation,
                                                              servant,
                                                              servant_state.in ()),
                      DISPATCH_REJECTED);

      // Just use the (base) request handle to hold the request object.
      request = req_ptr;
    }

  // Hand the request object to our task so that it can add the request
  // to its "request queue".
  if (!this->dtp_task_.add_request (request.in ()))
    {
      // Return the DISPATCH_REJECTED return code so that the caller (our
      // base class' dispatch_request() method) knows that we did
      // not handle the request, and that it should be rejected.
      return DISPATCH_REJECTED;
    }

  // We need to wait on the request object if the request type is a
  // synchronous request.
  if (!synch_request.is_nil ())
    {
      int srw = synch_request->wait ();
      if (srw == false)
        {
          // Raise exception when request was cancelled.
          throw ::CORBA::NO_IMPLEMENT ();
        }
    }
  else if (!synch_with_server_request.is_nil())
    {
      bool swsr = synch_with_server_request->wait();
      if (swsr == false)
        {
          // Raise exception when request was cancelled.
          throw ::CORBA::NO_IMPLEMENT ();
        }
    }

  return DISPATCH_HANDLED;
}
Example #12
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

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

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

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

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

      // Make all oneways "reliable."
      {
        CORBA::Object_var manager_object =
          orb->resolve_initial_references("ORBPolicyManager");
        CORBA::PolicyManager_var policy_manager =
          CORBA::PolicyManager::_narrow(manager_object.in());

        if (CORBA::is_nil (policy_manager.in ()))
          ACE_ERROR_RETURN ((LM_ERROR,
                             " (%P|%t) Panic: nil PolicyManager\n"),
                            1);
        CORBA::Any policy_value;
        policy_value <<= Messaging::SYNC_WITH_SERVER;
        CORBA::PolicyList policies(1); policies.length(1);
        policies[0] =
          orb->create_policy (Messaging::SYNC_SCOPE_POLICY_TYPE,
                              policy_value);

        policy_manager->set_policy_overrides (policies,
                                              CORBA::ADD_OVERRIDE);

        policies[0]->destroy ();
      }

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

      Service *service_impl;
      ACE_NEW_RETURN (service_impl,
                      Service(orb.in ()),
                      1);
      PortableServer::ServantBase_var owner_transfer(service_impl);

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

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

      Test::Service_var service =
        Test::Service::_narrow (object.in ());

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

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

      poa_manager->activate ();

      orb->run ();

      ACE_DEBUG ((LM_DEBUG, "Event loop finished\n"));

      service_impl->dump_results ();

      root_poa->destroy (1, 1);

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

  return 0;
}
Example #13
0
static int
test_active_map_manager (size_t table_size,
                         size_t iterations,
                         int test_iterators)
{
  ACTIVE_MAP_MANAGER map (table_size);
  TYPE i;
  TYPE j = 0;
  ssize_t k;

  ACTIVE_MAP_MANAGER::key_type *active_keys;

  ACE_NEW_RETURN (active_keys,
                  ACTIVE_MAP_MANAGER::key_type[iterations],
                  1);

  for (i = 0;
       i < iterations;
       i++)
    ACE_TEST_ASSERT (map.bind (i, active_keys[i]) != -1);

  if (test_iterators)
    {
      {
        i = 0;

        ACTIVE_MAP_MANAGER::iterator end = map.end ();

        for (ACTIVE_MAP_MANAGER::iterator iter = map.begin ();
             iter != end;
             ++iter)
          {
            ACTIVE_MAP_MANAGER::ENTRY &entry = *iter;
            ACE_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("(%d|%d-%d|%d)"),
                        i,
                        entry.ext_id_.slot_index (),
                        entry.ext_id_.slot_generation (),
                        entry.int_id_));
            ++i;
          }

        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("\n")));
        ACE_TEST_ASSERT (i == iterations);
      }

      {
        k = iterations - 1;

        ACTIVE_MAP_MANAGER::reverse_iterator rend = map.rend ();

        for (ACTIVE_MAP_MANAGER::reverse_iterator iter = map.rbegin ();
             iter != rend;
             ++iter)
          {
            ACTIVE_MAP_MANAGER::ENTRY &entry = *iter;
            ACE_UNUSED_ARG (entry);
            ACE_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("(%d|%d-%d|%d)"),
                        k,
                        entry.ext_id_.slot_index (),
                        entry.ext_id_.slot_generation (),
                        entry.int_id_));
            k--;
          }

        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("\n")));
        ACE_TEST_ASSERT (k == -1);
      }
    }

  for (i = 0; i < iterations; ++i)
    {
      ACE_TEST_ASSERT (map.find (active_keys[i], j) != -1);
      ACE_TEST_ASSERT (i == j);
    }

  size_t remaining_entries = iterations;
  for (i = 0; i < iterations; ++i)
    {
      ACE_TEST_ASSERT (map.unbind (active_keys[i]) != -1);
      --remaining_entries;
      ACE_TEST_ASSERT (map.current_size () == remaining_entries);
    }

  delete [] active_keys;

  return 0;
}
Example #14
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

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

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

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

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

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

      Simple_Server_i *server_impl = 0;
      ACE_NEW_RETURN (server_impl,
                      Simple_Server_i (orb.in ()),
                      -1);

      PortableServer::ServantBase_var owner_transfer(server_impl);

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

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

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

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

      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,
                               "(%P|%t) Cannot open output file for writing IOR: %s",
                               ior_output_file),
                              1);
          ACE_OS::fprintf (output_file, "%s", ior.in ());
          ACE_OS::fclose (output_file);
        }

      poa_manager->activate ();

      Worker worker (orb.in ());
      if (worker.activate (THR_NEW_LWP | THR_JOINABLE,
                           nthreads) != 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "(%P|%t) Cannot activate client threads\n"),
                          1);

      SelfClient selfabuse (orb.in(), server.in(), niterations);
      if (selfabuse.activate (THR_NEW_LWP | THR_JOINABLE,
                              nclient_threads) != 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "(%P|%t) Cannot activate abusive threads\n"),
                          1);

      selfabuse.thr_mgr()->wait();

      worker.thr_mgr ()->wait ();

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

  return 0;
}
Example #15
0
int test_orb (CORBA::ORB_ptr orb)
{
  int errors = 0;

  POA_TestModule::test* test = 0;
  ACE_NEW_RETURN (test,
                  test_i, 1);
  PortableServer::ServantBase_var safe (test);

  CORBA::Object_var object = test->_this ();

  orb->register_initial_reference ("ORBMyService",
                                    object.in ());

  bool invalid_name = false;
  try
    {
      // Registering with an empty string should give an exception
      orb->register_initial_reference ("",
                                       object.in ());
    }
  catch (const CORBA::ORB::InvalidName&)
    {
      invalid_name = true;
    }
  catch (const CORBA::Exception&)
    {
    }

  if (!invalid_name)
    {
      errors++;
      ACE_ERROR ((LM_ERROR, "ERROR: Registering with an empty string with the ORB"
                            "doesn't throw an exception\n"));
    }

  bool duplicate_name = false;
  try
    {
      // Registering with an duplicate string should give an exception
      orb->register_initial_reference ("ORBMyService",
                                        object.in ());
    }
  catch (const CORBA::ORB::InvalidName&)
    {
      duplicate_name = true;
    }
  catch (const CORBA::Exception&)
    {
    }

  if (!duplicate_name)
    {
      errors++;
      ACE_ERROR ((LM_ERROR, "ERROR: Registering with a duplicate with ORB "
                            "doesn't throw the expected exception\n"));
    }

  bool invalid_object = false;
  try
    {
      // Registering with a nil object
      orb->register_initial_reference ("ORBNilServer",
                                       CORBA::Object::_nil());
    }
  catch (const CORBA::BAD_PARAM& ex)
    {
      if ((ex.minor() & 0xFFFU) == 27)
        {
          invalid_object = true;
        }
    }
  catch (const CORBA::Exception&)
    {
    }

  if (!invalid_object)
    {
      errors++;
      ACE_ERROR ((LM_ERROR, "ERROR: Registering with a nil object to ORB "
                            "doesn't throw bad param with minor code 27\n"));
    }

  return errors;
}
Example #16
0
int
ACE_OS::string_to_argv (ACE_TCHAR *buf,
                        int &argc,
                        ACE_TCHAR **&argv,
                        int substitute_env_args)
{
  // Reset the number of arguments
  argc = 0;

  if (buf == 0)
    return -1;

  ACE_TCHAR *cp = buf;

  // First pass: count arguments.

  // '#' is the start-comment token..
  while (*cp != ACE_LIB_TEXT ('\0') && *cp != ACE_LIB_TEXT ('#'))
    {
      // Skip whitespace..
      while (ACE_OS::ace_isspace (*cp))
        cp++;

      // Increment count and move to next whitespace..
      if (*cp != ACE_LIB_TEXT ('\0'))
        argc++;

      while (*cp != ACE_LIB_TEXT ('\0') && !ACE_OS::ace_isspace (*cp))
        {
          // Grok quotes....
          if (*cp == ACE_LIB_TEXT ('\'') || *cp == ACE_LIB_TEXT ('"'))
            {
              ACE_TCHAR quote = *cp;

              // Scan past the string..
              for (cp++; *cp != ACE_LIB_TEXT ('\0') && *cp != quote; cp++)
                continue;

              // '\0' implies unmatched quote..
              if (*cp == ACE_LIB_TEXT ('\0'))
                {
                  argc--;
                  break;
                }
              else
                cp++;
            }
          else
            cp++;
        }
    }

  // Second pass: copy arguments.
  ACE_TCHAR arg[ACE_DEFAULT_ARGV_BUFSIZ];
  ACE_TCHAR *argp = arg;

  // Make sure that the buffer we're copying into is always large
  // enough.
  if (cp - buf >= ACE_DEFAULT_ARGV_BUFSIZ)
    ACE_NEW_RETURN (argp,
                    ACE_TCHAR[cp - buf + 1],
                    -1);

  // Make a new argv vector of argc + 1 elements.
  ACE_NEW_RETURN (argv,
                  ACE_TCHAR *[argc + 1],
                  -1);

  ACE_TCHAR *ptr = buf;

  for (int i = 0; i < argc; i++)
    {
      // Skip whitespace..
      while (ACE_OS::ace_isspace (*ptr))
        ptr++;

      // Copy next argument and move to next whitespace..
      cp = argp;
      while (*ptr != ACE_LIB_TEXT ('\0') && !ACE_OS::ace_isspace (*ptr))
        if (*ptr == ACE_LIB_TEXT ('\'') || *ptr == ACE_LIB_TEXT ('"'))
          {
            ACE_TCHAR quote = *ptr++;

            while (*ptr != ACE_LIB_TEXT ('\0') && *ptr != quote)
              *cp++ = *ptr++;

            if (*ptr == quote)
              ptr++;
          }
        else
          *cp++ = *ptr++;

      *cp = ACE_LIB_TEXT ('\0');

#if !defined (ACE_LACKS_ENV)
      // Check for environment variable substitution here.
      if (substitute_env_args) {
          argv[i] = ACE_OS::strenvdup(argp);

          if (argv[i] == 0)
            {
              if (argp != arg)
                delete [] argp;
              errno = ENOMEM;
              return -1;
            }
      }
      else
#endif /* ACE_LACKS_ENV */
        {
          argv[i] = ACE_OS::strdup(argp);

          if (argv[i] == 0)
            {
              if (argp != arg)
                delete [] argp;
              errno = ENOMEM;
              return -1;
            }
        }
    }

  if (argp != arg)
    delete [] argp;

  argv[argc] = 0;
  return 0;
}
Example #17
0
File: server.cpp Project: CCJY/ATCD
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  Fixed_Priority_Scheduler* scheduler=0;
  RTScheduling::Current_var current;
  long flags;
  int sched_policy = ACE_SCHED_RR;
  int sched_scope = ACE_SCOPE_THREAD;

  if (sched_policy == ACE_SCHED_RR)
    flags = THR_NEW_LWP | THR_BOUND | THR_JOINABLE | THR_SCHED_RR;
  else
    flags = THR_NEW_LWP | THR_BOUND | THR_JOINABLE | THR_SCHED_FIFO;

  task_stats.init (100000);

  try
    {
      RTScheduling::Scheduler_var sched_owner;

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

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

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

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

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

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

      if (enable_dynamic_scheduling)
        {
          CORBA::Object_var manager_obj =
            orb->resolve_initial_references ("RTSchedulerManager");

          TAO_RTScheduler_Manager_var manager =
            TAO_RTScheduler_Manager::_narrow (manager_obj.in ());

          Kokyu::DSRT_Dispatcher_Impl_t disp_impl_type;
          if (enable_yield)
            {
              disp_impl_type = Kokyu::DSRT_CV_BASED;
            }
          else
            {
              disp_impl_type = Kokyu::DSRT_OS_BASED;
            }

          ACE_NEW_RETURN (scheduler,
                          Fixed_Priority_Scheduler (orb.in (),
                                         disp_impl_type,
                                         sched_policy,
                                         sched_scope), -1);
          sched_owner = scheduler;

          manager->rtscheduler (scheduler);

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

          current  =
            RTScheduling::Current::_narrow (object.in ());
        }

      Simple_Server_i server_impl (orb.in (),
                                   current.in (),
                                   task_stats,
                                   enable_yield);

      Simple_Server_var server =
        server_impl._this ();

      CORBA::String_var ior =
        orb->object_to_string (server.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 ();

      Worker worker (orb.in ());
      if (worker.activate (flags,
                           nthreads,
                           0,
                           ACE_Sched_Params::priority_max(sched_policy,
                                                          sched_scope)) != 0)
        {
          ACE_ERROR ((LM_ERROR,
                      "Cannot activate threads in RT class.",
                      "Trying to activate in non-RT class\n"));

          flags = THR_NEW_LWP | THR_JOINABLE | THR_BOUND;
          if (worker.activate (flags, nthreads) != 0)
            {
              ACE_ERROR_RETURN ((LM_ERROR,
                                 "Cannot activate server threads\n"),
                                1);
            }
        }

      worker.wait ();

      ACE_DEBUG ((LM_DEBUG, "event loop finished\n"));

      ACE_DEBUG ((LM_DEBUG, "shutting down scheduler\n"));
      scheduler->shutdown ();

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

  ACE_DEBUG ((LM_DEBUG, "Exiting main...\n"));
  task_stats.dump_samples (ACE_TEXT("timeline.txt"),
                           ACE_TEXT("Time\t\tGUID"));
  return 0;
}
Example #18
0
int
ACE_Capabilities::fillent (const ACE_TCHAR *buf)
{
  this->resetcaps ();
  while (*buf)
    {
      ACE_TString s;
      int n;
      ACE_TString name;
      ACE_CapEntry *ce;

      // Skip blanks
      while (*buf && ACE_OS::ace_isspace(*buf)) buf++;
      // If we get end of line return

      if (*buf == ACE_TEXT ('\0'))
        break;

      if (*buf == ACE_TEXT ('#'))
        {
          while (*buf && *buf != ACE_TEXT ('\n'))
            buf++;
          if (*buf == ACE_TEXT ('\n'))
            buf++;
          continue;
        }
      while(*buf && *buf != ACE_TEXT ('=')
            && *buf!= ACE_TEXT ('#')
            && *buf != ACE_TEXT (','))
        name += *buf++;

      // If name is null.
      switch (*buf)
        {
        case ACE_TEXT ('='):
          // String property
          buf = this->parse (buf + 1, s);
          ACE_NEW_RETURN (ce,
                          ACE_StringCapEntry (s),
                          -1);
          if (this->caps_.bind (name, ce) == -1)
            {
              delete ce;
              return -1;
            }
          break;
        case ACE_TEXT ('#'):
          // Integer property
          buf = this->parse (buf + 1, n);
          ACE_NEW_RETURN (ce,
                          ACE_IntCapEntry (n),
                          -1);
          if (this->caps_.bind (name, ce) == -1)
            {
              delete ce;
              return -1;
            }
          break;
        case ACE_TEXT (','):
          // Boolean
          ACE_NEW_RETURN (ce,
                          ACE_BoolCapEntry (1),
                          -1);
          if (this->caps_.bind (name, ce) == -1)
            {
              delete ce;
              return -1;
            }
          break;
        default:
          return 0;
        }

      if (*buf++ != ACE_TEXT (','))
        return -1;
    }

  return 0;
}
Example #19
0
template <ACE_SYNCH_DECL> int
ACE_Stream<ACE_SYNCH_USE>::open (void *a,
                                 ACE_Module<ACE_SYNCH_USE> *head,
                                 ACE_Module<ACE_SYNCH_USE> *tail)
{
    ACE_TRACE ("ACE_Stream<ACE_SYNCH_USE>::open");
    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX_T, ace_mon, this->lock_, -1);

    ACE_Task<ACE_SYNCH_USE> *h1 = 0, *h2 = 0;
    ACE_Task<ACE_SYNCH_USE> *t1 = 0, *t2 = 0;

    if (head == 0)
    {
        ACE_NEW_RETURN (h1,
                        ACE_Stream_Head<ACE_SYNCH_USE>,
                        -1);
        ACE_NEW_RETURN (h2,
                        ACE_Stream_Head<ACE_SYNCH_USE>,
                        -1);
        ACE_NEW_RETURN (head,
                        ACE_Module<ACE_SYNCH_USE> (ACE_TEXT ("ACE_Stream_Head"),
                                h1, h2,
                                a,
                                M_DELETE),
                        -1);
    }

    if (tail == 0)
    {
        ACE_NEW_RETURN (t1,
                        ACE_Stream_Tail<ACE_SYNCH_USE>,
                        -1);
        ACE_NEW_RETURN (t2,
                        ACE_Stream_Tail<ACE_SYNCH_USE>,
                        -1);
        ACE_NEW_RETURN (tail,
                        ACE_Module<ACE_SYNCH_USE> (ACE_TEXT ("ACE_Stream_Tail"),
                                t1, t2,
                                a,
                                M_DELETE),
                        -1);
    }

    // Make sure *all* the allocation succeeded!
    if ((head == 0 && (h1 == 0 || h2 == 0))
            || (tail == 0 && (t1 == 0 || t2 == 0)))
    {
        delete h1;
        delete h2;
        delete t1;
        delete t2;
        delete head;
        delete tail;
        errno = ENOMEM;
        return -1;
    }

    this->stream_head_ = head;
    this->stream_tail_ = tail;

    if (this->push_module (this->stream_tail_) == -1)
        return -1;
    else if (this->push_module (this->stream_head_,
                                this->stream_tail_,
                                this->stream_head_) == -1)
        return -1;

    return 0;
}
Example #20
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

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

      if (CORBA::is_nil (poa_object.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("SERVER: Unable to initialize the POA.\n")),
                          1);

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

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

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

      // Servant
      test_i *servant = 0;
      ACE_NEW_RETURN (servant,
                      test_i (0, orb.in ()),
                      -1);
      PortableServer::ServantBase_var safe (servant);

      PortableServer::ObjectId_var oid =
        root_poa->activate_object (servant);

      CORBA::Object_var obj =
        root_poa->servant_to_reference (servant);

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

      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("SERVER: test_i servant: <%C>\n"),
                  ior.in ()));

      poa_manager->activate ();

      // IOR
      FILE *output_file= ACE_OS::fopen (ior_file, "w");
      if (output_file == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("SERVER: Cannot open output file <%s> ")
                           ACE_TEXT ("for writting IOR: %C"),
                           ior_file,
                           ior.in ()),
                          1);
      ACE_OS::fprintf (output_file, "%s", ior.in ());
      ACE_OS::fclose (output_file);

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

      root_poa->destroy (1, 1);

      orb->destroy ();

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("SERVER: Event loop finished.\n")));
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Caught exception:");
      return -1;
    }

  return 0;
}
Example #21
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

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

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

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

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

      Foo_Bar *foobar_impl;
      ACE_NEW_RETURN (foobar_impl,
                      Foo_Bar (orb.in ()),
                      1);

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

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

      Test::Foo_var foo =
        Test::Foo::_narrow (object.in ());

      poa_manager->activate ();

      // Dont unscope it or move it elsewhere.. It is here with a
      // purpose. If you dont understand this, please re-read the
      // README file.
      {
        PortableServer::ServantBase_var owner_transfer (foobar_impl);
      }

      ACE_Time_Value tv (10,
                         0);

      // Just run the ORB for a minute..
      orb->run (tv);

      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) server - shutting down the ORB\n"));

      orb->shutdown (1);

      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) Finished shutting down the ORB\n"));

      root_poa->destroy (1, 1);

      orb->destroy ();

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

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t) Test successful..\n"));
  return 0;
}
Example #22
0
 virtual PSession*  create_session(PSessionManager & /*manager*/)
   {
     PSession * p = 0;
     ACE_NEW_RETURN (p, Sender, 0);
     return p;
   }
int
Load_Balancing_Service::init (int argc, ACE_TCHAR* argv[])
{
  int result;
  CORBA::String_var ior;

  try
    {
      result = this->orb_manager_.init (argc, argv);
      if (result == -1)
        return result;

      // Check the non-ORB arguments.
      result = this->parse_args (argc, argv);
      if (result < 0)
        return result;


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

      // Lifespan policy
      policies[0] =
        this->orb_manager_.root_poa()->create_lifespan_policy (PortableServer::PERSISTENT);

      policies[1] =
        this->orb_manager_.root_poa()->create_implicit_activation_policy (PortableServer::IMPLICIT_ACTIVATION);

      PortableServer::POA_var persistent_POA =
        this->orb_manager_.root_poa()->create_POA ("persistent",
                                                   this->orb_manager_.poa_manager (),
                                                   policies);


      // Destroy policy objects
      for (CORBA::ULong i = 0;
           i < policies.length ();
           ++i)
        {
          policies[i]->destroy ();
        }

      // Create, ref. count, and activate the servant.
      Object_Group_Factory_i * factory_servant;
      ACE_NEW_RETURN (factory_servant,
                      Object_Group_Factory_i (this->orb_manager_.orb (),
                                              persistent_POA.in ()),
                      -1);

      // Activate the POA manager
      //PortableServer::ServantBase_var s = factory_servant;
      this->orb_manager_.activate_poa_manager ();

      CORBA::Object_var objref = factory_servant->_this ();

      ior = this->orb_manager_.orb ()->object_to_string (objref.in ());

      if (ior.in () == 0)
        return -1;
      else if (TAO_debug_level > 0)
        ACE_DEBUG ((LM_DEBUG,
                    "Object Group Factory ior: %s\n",
                    ior.in ()));
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Load_Balancing_Service::init");
      return -1;
    }

  if (this->ior_output_file_ != 0)
    {
      ACE_OS::fprintf (this->ior_output_file_,
                       "%s",
                       ior.in ());
      ACE_OS::fclose (this->ior_output_file_);
    }
  return 0;
}
Example #24
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

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

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

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

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

      // Make all oneways "reliable."
      {
        CORBA::Object_var manager_object =
          orb->resolve_initial_references("ORBPolicyManager");
        CORBA::PolicyManager_var policy_manager =
          CORBA::PolicyManager::_narrow(manager_object.in());

        if (CORBA::is_nil (policy_manager.in ()))
          ACE_ERROR_RETURN ((LM_ERROR,
                             " (%P|%t) Panic: nil PolicyManager\n"),
                            1);
        CORBA::Any policy_value;
        policy_value <<= Messaging::SYNC_WITH_SERVER;
        CORBA::PolicyList policies(1); policies.length(1);
        policies[0] =
          orb->create_policy (Messaging::SYNC_SCOPE_POLICY_TYPE,
                              policy_value);

        policy_manager->set_policy_overrides (policies,
                                              CORBA::ADD_OVERRIDE);

        policies[0]->destroy ();
      }

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

      CORBA::Object_var tmp =
        orb->string_to_object(ior);

      Test::Service_var service =
        Test::Service::_narrow(tmp.in ());

      if (CORBA::is_nil (service.in ()))
        {
          ACE_ERROR_RETURN ((LM_DEBUG,
                             "Nil service reference <%s>\n",
                             ior),
                            1);
        }

      Callback *callback_impl;
      ACE_NEW_RETURN (callback_impl,
                      Callback(orb.in ()),
                      1);
      PortableServer::ServantBase_var owner_transfer(callback_impl);

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

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

      Test::Callback_var callback =
        Test::Callback::_narrow (object.in ());

      poa_manager->activate ();

      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) client - starting test\n"));

      service->run_test (callback.in ());

      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) client - running ORB\n"));

      orb->run ();

      root_poa->destroy (1, 1);

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

  return 0;
}
Example #25
0
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  // Construct a new thread manager for the input device task.  Auto
  // ptr ensures memory is freed when we exit this scope.
  ACE_Thread_Manager *input_task_mgr;
  ACE_NEW_RETURN (input_task_mgr,
                  ACE_Thread_Manager,
                  -1);
  auto_ptr <ACE_Thread_Manager> mgr (input_task_mgr);

  // Construct a new input device wrapper.  Auto ptr ensures memory is
  // freed when we exit this scope.
  Text_Input_Device_Wrapper *input_device;
  ACE_NEW_RETURN (input_device,
                  Text_Input_Device_Wrapper (input_task_mgr,
                                             sizeof (input_text),
                                             input_text),
                  -1);
  auto_ptr <Text_Input_Device_Wrapper> input (input_device);

  // Construct a new output device wrapper.  Auto ptr ensures memory
  // is freed when we exit this scope.
  Text_Output_Device_Wrapper *output_device = 0;
  ACE_NEW_RETURN (output_device,
                  Text_Output_Device_Wrapper,
                  -1);
  auto_ptr <Text_Output_Device_Wrapper> output (output_device);

  // Construct a new bounded packet relay.  Auto ptr ensures memory is
  // freed when we exit this scope.
  Bounded_Packet_Relay *packet_relay = 0;
  ACE_NEW_RETURN (packet_relay,
                  Bounded_Packet_Relay (input_task_mgr,
                                        input_device,
                                        output_device),
                  -1);
  auto_ptr <Bounded_Packet_Relay> relay (packet_relay);

  // Construct a receive input callback command for the relay, and register
  // it with the input device.  Auto ptr ensures memory is freed when we exit
  // this scope.
  INPUT_CALLBACK *input_callback = 0;
  ACE_NEW_RETURN (input_callback,
                  INPUT_CALLBACK (*packet_relay,
                                  &Bounded_Packet_Relay::receive_input),
                  -1);
  auto_ptr <INPUT_CALLBACK> callback (input_callback);
  if (input_device->set_send_input_msg_cmd (input_callback) < 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         "failed to register input callback"),
                        -1);
    }

  // Construct a new bounded packet relay driver.  Auto ptr ensures
  // memory is freed when we exit this scope.
  THREAD_BOUNDED_PACKET_RELAY_DRIVER *tbprd = 0;

  ACE_NEW_RETURN (tbprd,
                  Thread_Bounded_Packet_Relay_Driver (packet_relay),
                  -1);

  auto_ptr <THREAD_BOUNDED_PACKET_RELAY_DRIVER> driver (tbprd);

  return driver->run ();
  // All dynamically allocated memory is released when main() returns.
}
Example #26
0
/// Gets a list of the files in the archive.
int ZIP_Wrapper::file_list_info (char* zip_name,
                                 ACE_Double_Linked_List<ZIP_File_Info> &list)
{
  unzFile uf=0;
  char filename_try[MAXFILENAME+16] = "";
  if (zip_name!=0)
    {
      ACE_OS::strncpy(filename_try, zip_name, MAXFILENAME-1);
      /* strncpy doesnt append the trailing NULL, if the string is too long. */
      filename_try[ MAXFILENAME ] = '\0';
      /* open the zip file */
      uf = unzOpen(zip_name);
      /* if zipfile could not be opened, try appending .zip to name */
      if (uf==0)
        {
          ACE_OS::strcat(filename_try, ".zip");
          uf = unzOpen(filename_try);
        }
    }
  /* If zipfile could not be opened still, return */
  if (uf==0)
    {
      DANCE_ERROR (DANCE_LOG_ERROR,
                   (LM_DEBUG, ACE_TEXT("There is some problem in opening")
                    ACE_TEXT(" %s or %s.zip using unzOpen\n"), zip_name, zip_name));
      return 1;
    }
  unz_global_info gi;
  /* get information about all the files in zip file*/
  int err = unzGetGlobalInfo(uf, &gi);
  if (err!=UNZ_OK)
    DANCE_ERROR (DANCE_LOG_ERROR,
                 (LM_DEBUG, ACE_TEXT("unzGetGlobalInfo failed while trying")
                  ACE_TEXT(" to get global information about zipfile\n"), err));
  /* gi.number_entry corresponds to the number of directory entries
     in the zip file */
  for (uLong i=0;i<gi.number_entry;i++)
    {
      char filename_inzip[256];
      unz_file_info file_info;
      /* get information about the current file in zip file */
      err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip,
                                  sizeof(filename_inzip), 0, 0, 0, 0);
      if (err!=UNZ_OK)
        {
          DANCE_ERROR (DANCE_LOG_ERROR,
                       (LM_DEBUG, ACE_TEXT("unzGetCurrentFileInfo failed")
                        ACE_TEXT(" while trying to get information")
                        ACE_TEXT(" about current file\n"), err));
          break;
        }
      ZIP_File_Info* next = 0;
      ACE_NEW_RETURN (next, ZIP_File_Info (filename_inzip,
                      sizeof(filename_inzip)), -1);
      /* add information about current file to the list */
      list.insert_tail (next);
      if ((i+1)<gi.number_entry)
        {
          err = unzGoToNextFile(uf);
          if (err!=UNZ_OK)
          {
            DANCE_ERROR (DANCE_LOG_ERROR,
                         (LM_DEBUG,
                          ACE_TEXT(" unzGoToNextFile failed")
                          ACE_TEXT(" while trying to go to next file\n"),
                          err));
            break;
          }
        }
    }
  unzCloseCurrentFile(uf);
  return gi.number_entry;
}
Example #27
0
pid_t
ACE_Process_Manager::wait (pid_t pid,
                           const ACE_Time_Value &timeout,
                           ACE_exitcode *status)
{
  ACE_TRACE ("ACE_Process_Manager::wait");

  ACE_exitcode local_stat = 0;
  if (status == 0)
    status = &local_stat;

  *status = 0;

  ssize_t idx = -1;
  ACE_Process *proc = 0;

  {
    // fake context after which the lock is released
    ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));

    if (pid != 0)
      {
        idx = this->find_proc (pid);
        if (idx == -1)
          return ACE_INVALID_PID;
        else
          proc = process_table_[idx].process_;
      }
    // release the lock.
  }
  if (proc != 0)
    pid = proc->wait (timeout, status);
  else
    {
      ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));
      // Wait for any Process spawned by this Process_Manager.
#if defined (ACE_WIN32)
      HANDLE *handles = 0;

      ACE_NEW_RETURN (handles,
                      HANDLE[this->current_count_],
                      ACE_INVALID_PID);

      for (size_t i = 0;
           i < this->current_count_;
           ++i)
        handles[i] =
          process_table_[i].process_->gethandle ();

      DWORD handle_count = static_cast<DWORD> (this->current_count_);
      DWORD result = ::WaitForMultipleObjects (handle_count,
                                               handles,
                                               FALSE,
                                               timeout == ACE_Time_Value::max_time
                                               ? INFINITE
                                               : timeout.msec ());
      if (result == WAIT_FAILED)
        pid = ACE_INVALID_PID;
      else if (result == WAIT_TIMEOUT)
        pid = 0;
      else
        {
          // Green Hills produces a warning that result >=
          // WAIT_OBJECT_0 is a pointless comparison because
          // WAIT_OBJECT_0 is zero and DWORD is unsigned long, so this
          // test is skipped for Green Hills.  Same for mingw.
# if defined (__MINGW32__) || defined (_MSC_VER)
          ACE_ASSERT (result < WAIT_OBJECT_0 + this->current_count_);
# else
          ACE_ASSERT (result >= WAIT_OBJECT_0
                      && result < WAIT_OBJECT_0 + this->current_count_);
# endif

          idx = this->find_proc (handles[result - WAIT_OBJECT_0]);

          if (idx != -1)
            {
              pid = process_table_[idx].process_->getpid ();
              result = ::GetExitCodeProcess (handles[result - WAIT_OBJECT_0],
                                             status);
              if (result == 0)
                {
                  // <GetExitCodeProcess> failed!
                  this->remove_proc (idx);
                  pid = ACE_INVALID_PID;
                }
            }
          else
            {
              // uh oh...handle removed from process_table_, even though
              // we're holding a lock!
              delete [] handles;
              ACELIB_ERROR_RETURN ((LM_ERROR,
                                 ACE_TEXT ("Process removed")
                                 ACE_TEXT (" -- somebody's ignoring the lock!\n")),
                                -1);
            }
        }

      delete [] handles;
#else /* !defined(ACE_WIN32) */
      if (timeout == ACE_Time_Value::max_time)
        pid = ACE_OS::waitpid (-1, status, 0);
      else if (timeout == ACE_Time_Value::zero)
        pid = ACE_OS::waitpid (-1, status, WNOHANG);
      else
        {
# if defined (ACE_LACKS_UNIX_SIGNALS)
          pid = 0;
          ACE_Time_Value sleeptm (1);    // 1 msec
          if (sleeptm > timeout)         // if sleeptime > waittime
            sleeptm = timeout;
          ACE_Time_Value tmo (timeout);  // Need one we can change
          for (ACE_Countdown_Time time_left (&tmo); tmo > ACE_Time_Value::zero ; time_left.update ())
            {
              pid = ACE_OS::waitpid (-1, status, WNOHANG);
              if (pid > 0 || pid == ACE_INVALID_PID)
                break;          // Got a child or an error - all done

              // pid 0, nothing is ready yet, so wait.
              // Do a (very) short sleep (only this thread sleeps).
              ACE_OS::sleep (sleeptm);
            }
# else
          // Force generation of SIGCHLD, even though we don't want to
          // catch it - just need it to interrupt the sleep below.
          // If this object has a reactor set, assume it was given at
          // open(), and there's already a SIGCHLD action set, so no
          // action is needed here.
          ACE_Sig_Action old_action;
          if (this->reactor () == 0)
            {
              ACE_Sig_Action do_sigchld ((ACE_SignalHandler)sigchld_nop);
              do_sigchld.register_action (SIGCHLD, &old_action);
            }

          ACE_Time_Value tmo (timeout);  // Need one we can change
          for (ACE_Countdown_Time time_left (&tmo); ; time_left.update ())
            {
              pid = ACE_OS::waitpid (-1, status, WNOHANG);
#   if defined (ACE_VXWORKS)
              if (pid > 0 || (pid == ACE_INVALID_PID && errno != EINTR))
#   else
                if (pid > 0 || pid == ACE_INVALID_PID)
#   endif
                  break;          // Got a child or an error - all done

              // pid 0, nothing is ready yet, so wait.
              // Do a sleep (only this thread sleeps) til something
              // happens. This relies on SIGCHLD interrupting the sleep.
              // If SIGCHLD isn't delivered, we'll need to do something
              // with sigaction to force it.
              if (-1 == ACE_OS::sleep (tmo) && errno == EINTR)
                continue;
              // Timed out
              pid = 0;
              break;
            }

          // Restore the previous SIGCHLD action if it was changed.
          if (this->reactor () == 0)
            old_action.register_action (SIGCHLD);
# endif /* !ACE_LACKS_UNIX_SIGNALS */
        }
#endif /* !defined (ACE_WIN32) */
    }

  ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));
  if (pid != ACE_INVALID_PID && pid != 0)
    {
      //we always need to get our id, because we could have been moved in the table meanwhile
      idx = this->find_proc (pid);
      if (idx == -1)
        {
          // oops, reaped an unmanaged process!
          ACELIB_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) oops, reaped unmanaged %d\n"),
                      pid));
          return pid;
        }
      else
        proc = process_table_[idx].process_;
      if (proc != 0)
        ACE_ASSERT (pid == proc->getpid ());

      this->notify_proc_handler (idx,
                                 *status);
      this->remove (pid);
    }

  return pid;
}
int
ACE_SOCK_SEQPACK_Association::get_local_addrs (ACE_INET_Addr *addrs, size_t &size) const
{
  ACE_TRACE ("ACE_SOCK_SEQPACK_Association::get_local_addrs");

#if defined (ACE_HAS_LKSCTP)
  /*
    The size of ACE_INET_Addr must be large enough to hold the number of
    local addresses on the machine.  If the array is too small, the function
    will only return the number of addresses that will fit.  If the array is
    too large, the 'size' parameter will be modified to indicate the number
    of addrs.

    We will call sctp_getladdrs() which accepts 3 parameters
    1. a socket fd
    2. a sctp association_id which will be ignored since we are using
       tcp sockets
    3. a pointer to sockaddr

    lksctp/draft will allocate memory and we are responsible for freeing
    it by calling sctp_freeladdrs().
  */

  sockaddr_in *si = 0;
  sockaddr *laddrs = 0;
  int err = 0;
  size_t len = 0;

#ifndef ACE_HAS_VOID_PTR_SCTP_GETLADDRS
  err = sctp_getladdrs(this->get_handle(), 0, &laddrs);
#else
  err = sctp_getladdrs(this->get_handle(), 0, reinterpret_cast<void**>(&laddrs));
#endif /* ACE_HAS_VOID_PTR_SCTP_GETPADDRS */
  if (err > 0)
  {
    len = err;
    // check to see if we have more addresses than we have
    // space in our ACE_INET_Addr array
    if (len > size)
    {
      // since our array is too small, we will only copy the first
      // few that fit
      len = size;
    }

    for (size_t i = 0; i < len; i++)
    {
      // first we cast the sockaddr to sockaddr_in
      // since we only support ipv4 at this time.
      si = (sockaddr_in *) (&(laddrs[i]));

      // now we fillup the ace_inet_addr array
      addrs[i].set_addr(si, sizeof(sockaddr_in));
      addrs[i].set_type(si->sin_family);
      addrs[i].set_size(sizeof(sockaddr_in));
    }
  }
  else /* err < 0 */
  {
    // sctp_getladdrs will return -1 on error
    return -1;
  }

  // indicate the num of addrs returned to the calling function
  size = len;

  // make sure we free the struct using the system function
  sctp_freeladdrs(laddrs);

#else

  /*
    We will be calling ACE_OS::getsockname, which accepts (and
    potentially modifies) two reference parameters:

    1.  a sockaddr_in* that points to a buffer
    2.  an int* that points to the size of this buffer

    The OpenSS7 implementation of SCTP copies an array of ipv4
    sockaddr_in into the buffer.  Then, if the size of the buffer is
    greater than the size used, the size parameter is reduced
    accordingly.

  */

  // The array of sockaddr_in will be stored in an ACE_Auto_Array_Ptr,
  // which causes dynamically-allocated memory to be released as soon
  // as the ACE_Auto_Array_Ptr goes out of scope.
  ACE_Auto_Array_Ptr<sockaddr_in> addr_structs;

  // Allocate memory for this array.  Return -1 if the memory cannot
  // be allocated.  (This activity requires a temporary variable---a
  // bare sockaddr_in* --- because ACE_NEW_RETURN cannot act directory on
  // an ACE_Auto_Array_Ptr.)
  {
    sockaddr_in *addr_structs_bootstrap = 0;
    ACE_NEW_RETURN (addr_structs_bootstrap, sockaddr_in[size], -1);
    addr_structs.reset(addr_structs_bootstrap);
  }

  // Physical size of this array is its logical size multiplied by
  // the physical size of one of its elements.
  size_t physical_size = size * sizeof(sockaddr_in);

  /* Clear the array */
  ACE_OS::memset(addr_structs.get(),
                 0,
                 physical_size);

  /*
  ** Populate the array with real values from the getsockname system
  ** call.  addr_structs is modified, and name_size is modified to contain
  ** the number of bytes written to addr_structs.
  ** Use name_size to get the data types right across the call.
  */
  int name_size = static_cast<int> (physical_size);
  if (ACE_OS::getsockname (this->get_handle (),
                           reinterpret_cast<sockaddr *> (addr_structs.get()),
                           &name_size) == -1)
    return -1;

  /* Calculate the NEW physical size of the array */
  name_size /= sizeof (sockaddr_in);
  size = static_cast<size_t> (name_size);

  /* Copy each sockaddr_in to the address structure of an ACE_Addr from
     the passed-in array */
  const int addrlen (static_cast<int> (sizeof (sockaddr_in)));
  for (int i = 0; i < name_size; ++i)
    {
      addrs[i].set_addr (&(addr_structs[i]), addrlen);
      addrs[i].set_type (addr_structs[i].sin_family);
      addrs[i].set_size (addrlen);
    }
#endif /* ACE_HAS_LKSCTP */
  return 0;
}
Example #29
0
ACE_Message_Block *
ACE_Message_Block::duplicate (void) const
{
  ACE_TRACE ("ACE_Message_Block::duplicate");

  ACE_Message_Block *nb = 0;

  // Create a new <ACE_Message_Block> that contains unique copies of
  // the message block fields, but a reference counted duplicate of
  // the <ACE_Data_Block>.

  // If there is no allocator, use the standard new and delete calls.
  if (this->message_block_allocator_ == 0)
    ACE_NEW_RETURN (nb,
                    ACE_Message_Block (0, // size
                                       ACE_Message_Type (0), // type
                                       0, // cont
                                       0, // data
                                       0, // allocator
                                       0, // locking strategy
                                       0, // flags
                                       this->priority_, // priority
                                       ACE_EXECUTION_TIME,
                                       ACE_DEADLINE_TIME,
                                       // Get a pointer to a
                                       // "duplicated" <ACE_Data_Block>
                                       // (will simply increment the
                                       // reference count).
                                       this->data_block ()->duplicate  (),
                                       this->data_block ()->data_block_allocator (),
                                       this->message_block_allocator_),
                  0);
  else // Otherwise, use the message_block_allocator passed in.
    ACE_NEW_MALLOC_RETURN (nb,
                           static_cast<ACE_Message_Block*> (
                             message_block_allocator_->malloc (sizeof (ACE_Message_Block))),
                           ACE_Message_Block (0, // size
                                              ACE_Message_Type (0), // type
                                              0, // cont
                                              0, // data
                                              0, // allocator
                                              0, // locking strategy
                                              0, // flags
                                              this->priority_, // priority
                                              ACE_EXECUTION_TIME,
                                              ACE_DEADLINE_TIME,
                                              // Get a pointer to a
                                              // "duplicated" <ACE_Data_Block>
                                              // (will simply increment the
                                              // reference count).
                                              this->data_block ()->duplicate  (),
                                              this->data_block ()->data_block_allocator (),
                                              this->message_block_allocator_),
                           0);

  // Set the read and write pointers in the new <Message_Block> to the
  // same relative offset as in the existing <Message_Block>.  Note
  // that we are assuming that the data_block()->base() pointer
  // doesn't change when it's duplicated.
  nb->rd_ptr (this->rd_ptr_);
  nb->wr_ptr (this->wr_ptr_);

  // Increment the reference counts of all the continuation messages.
  if (this->cont_)
    {
      nb->cont_ = this->cont_->duplicate ();

      // If things go wrong, release all of our resources and return
      // 0.
      if (nb->cont_ == 0)
        {
          nb->release ();
          nb = 0;
        }
    }

  return nb;
}
Example #30
0
int CellAcceptor::handle_input(ACE_HANDLE fd) {
    //ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)CellAcceptor::handle_input - New incoming connection\n")));
    CellSvcHandler *client;
    ThreadPerConnection *tpc = new ThreadPerConnection();
    //ACE_Strong_Bound_Ptr<ThreadPerConnection, ACE_Recursive_Thread_Mutex>* tpcPrt = new
      //      ACE_Strong_Bound_Ptr<ThreadPerConnection, ACE_Recursive_Thread_Mutex > (tpc);
    ExecutionModelPtr* tpcPrt = new ExecutionModelPtr (tpc);
    ACE_NEW_RETURN(client,
            CellSvcHandler(m_cell,  tpcPrt, 0, 0, 0), -1);

    auto_ptr<CellSvcHandler> p(client);
    if (this->m_acceptor.accept(client->peer()) == -1)
        ACE_ERROR_RETURN((LM_ERROR,
            ACE_TEXT("(%T) failed to accept\n")),
            -1);
    p.release();

    ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO CellAcceptor::handle_input - new connection %d!\n"), client->get_handle()));
    CPUPriorityQoS* cpuQoS = new CPUPriorityQoS(CPUQoS::SCHEDULE_RT_DEFAULT, CPUQoS::MAX_RT_PRIO);
    CPUReservation* reserve = 0;
    if (m_cell->getQoSManager() != 0) {
        reserve = m_cell->getQoSManager()->createCPUReservation("HRT", cpuQoS);
    }
    //printf("==================== %p %p \n\n\n\n",cpuQoS,reserve);
    tpc->bind(client);
    tpc->open(reserve, cpuQoS);

    if (client->open() == -1) {
        printf("CellAcceptor: failed to eopn client == -1\n");
        delete client;
        return 0;
    }
    UUIDPtr uuid;
    m_cell->getPID(uuid);
    UUIDPtr fid;
    m_cell->getFID(fid);
    CellIDPtr cellID;
    m_cell->getCellID(cellID);
    if (client->isLeaf()) {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: CellAcceptor::handle_input() - Add new children peer (%s,%s)\n"),
                cellID->toString().c_str(), client->getCellID()->toString().c_str()));
        if(m_leafGroup->add(client) == -1){
            return 0;
        }
    } else {
        if (client->isChildren()) {
            CellIDPtr runtimeCellID;
            m_cell->getCellID(runtimeCellID);
            ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: CellAcceptor::handle_input() - Add new children peer (%s,%s)\n"),
                    runtimeCellID->toString().c_str(), client->getCellID()->toString().c_str()));
            if(m_childrenGroup->add(client)==-1){
                return 0;
            }
        } else {
            ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: CellAcceptor::handle_input() - Add group peer\n")));
            if(m_cellGroup->add(client) == -1){
                return 0;
            }
            ACE_Connector<CellFollowerClientHandler, ACE_SOCK_Connector> connector;
            ThreadPerConnection *tpc = new ThreadPerConnection();
            //ACE_Strong_Bound_Ptr<ThreadPerConnection, ACE_Recursive_Thread_Mutex>* tpcPrt = new
            //        ACE_Strong_Bound_Ptr<ThreadPerConnection, ACE_Recursive_Thread_Mutex > (tpc);
            ExecutionModelPtr* tpcPrt = new ExecutionModelPtr(tpc);

            CellFollowerClientHandler* followerClient = new CellFollowerClientHandler(
                    client->getPID(), client->getFID(), m_cell,
                    //true, false,
                    false,false,
                    tpcPrt,
                    0, 0, 0);

            CPUQoS* followerCPUQoS = new CPUPriorityQoS(CPUQoS::SCHEDULE_RT_DEFAULT, CPUQoS::MAX_RT_PRIO);
            CPUReservation* followerReserve = 0;
            if (m_cell->getQoSManager() != 0) {
                followerReserve = m_cell->getQoSManager()->createCPUReservation("HRT", cpuQoS);
            }

            tpc->bind(followerClient);
            tpc->open(followerReserve,followerCPUQoS);
            connector.reactor(tpc->getResources()->getReactor());

            ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: Connecting to follower...(%s)!\n"), client->getPID()->toString().c_str()));

            if (connector.connect(followerClient, client->getFollowerEndpoint()->getAddr()) == -1) {
                ACE_ERROR((LM_ERROR, ACE_TEXT("CellAcceptor::handle_input follower connection failed\n")));
                followerClient->close();
                throw ServiceException("Error connecting to follower!");
            } else {
                ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: Cell:joinNonCoordinator() - Connect OK!\n")));
            }

            if(m_cellFollowerGroup->add(followerClient) == -1){
                client->close();
                return 0;
            }
            if (followerClient->asynchronous(true, false)) {
                followerClient->close();
            }
        }
    }
    //if (client->asynchronous(true, true) == -1) {
    //changed:
    if (client->asynchronous(true, false) == -1) {
        client->close();
    }

    ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: client binded OK!\n")));
    return 0;
}