Exemplo n.º 1
0
    /*!
     * Returns the element for the pair (p1, p2), either by retrieving an
     * existing element (see \ref retrieveElement) or by creating a new one, if
     * no element for that pair exists yet.
     *
     * \return Either the value of \ref retrieveElement or a new element for
     * (p1,p2), if \ref retrieveElement returns NULL.
     */
    CollisionCacheElement* CollisionCache::retrieveOrAddElement(Proxy* p1, Proxy* p2) {
        if (!p1) {
            throw NullPointerException("p1");
        }
        if (!p2) {
            throw NullPointerException("p2");
        }

        CollisionCacheElement* element = retrieveElement(p1, p2);
        if (element) {
            return element;
        }

        element = new CollisionCacheElement(p1, p2);

        element->mCachePosition1 = mMap.insert(std::make_pair(p1, element));

        //insert the second element only for non-selfcollisions
        if (p1 != p2) {
            element->mCachePosition2 = mMap.insert(std::make_pair(p2, element));
        } else {
            element->mCachePosition2 = element->mCachePosition1;
        }

        return element;
    }
Exemplo n.º 2
0
std::istream& RouteCost::load(std::istream& input)
{
//    if (CityMap::Instance().fileLength < 5*sizeof(int)) {
//        throw NullPointerException();
//    }
//    CityMap::Instance().fileLength -= 5*sizeof(int);

    char intBuf[sizeof(int)];
    memset(intBuf,0,sizeof(int));
    input.read(intBuf, sizeof(int));
    moneyCost = *(reinterpret_cast<int*>(intBuf));
    std::cout << "read moneyCost "<<moneyCost<<std::endl;

    int hour,min,sec;
    input.read(intBuf, sizeof(int));
    hour = *(reinterpret_cast<int*>(intBuf));
    input.read(intBuf, sizeof(int));
    min = *(reinterpret_cast<int*>(intBuf));
    input.read(intBuf, sizeof(int));
    sec = *(reinterpret_cast<int*>(intBuf));
    this->timeCost = QTime(hour, min, sec);

    std::cout << "read time "<<hour<<" "<<min<<" "<<sec<<std::endl;

    input.read(intBuf, sizeof(int));
    unsigned int interestsCount = *(reinterpret_cast<int*>(intBuf));
    interests = std::set<Interest>();

    if (interestsCount > 20) {
        throw NullPointerException();
    }

    std::cout<<"read interests count "<<interestsCount << std::endl;

    for (int i = 0; i < interestsCount; i++) {
        input.read(intBuf, sizeof(int));
        Interest interest = *(reinterpret_cast<Interest*>(intBuf));
        interests.insert(interest);
    }

    input.read(intBuf, sizeof(int));
    unsigned int transportsCount = *(reinterpret_cast<int*>(intBuf));
    transports = std::set<Transport>();

    if (transportsCount > 20) {
        throw NullPointerException();
    }

    std::cout<<"read transports count "<<transportsCount << std::endl;

    for (int i = 0; i < transportsCount; i++) {
        input.read(intBuf, sizeof(int));
        Transport transport = *(reinterpret_cast<Transport*>(intBuf));
        transports.insert((Transport) transport);
    }

    return input;
}
Exemplo n.º 3
0
/** Add one thread.
 * Add the given thread to the thread manager. The thread is initialized
 * as appropriate and started. See the class documentation for supported
 * specialisations of threads and the performed initialisation steps.
 * If the thread initializer cannot initalize the thread it is not added.
 * @param thread thread to add
 * @param lock if true the environment is locked before adding the thread
 * @exception CannotInitializeThreadException thrown if at least the
 * thread could not be initialised
 */
void
ThreadManager::add_maybelocked(Thread *thread, bool lock)
{
  if ( thread == NULL ) {
    throw NullPointerException("FawkesThreadMananger: cannot add NULL as thread");
  }

  if ( ! (__initializer && __finalizer) ) {
    throw NullPointerException("ThreadManager: initializer/finalizer not set");
  }

  try {
    __initializer->init(thread);
  } catch (CannotInitializeThreadException &e) {
    thread->notify_of_failed_init();
    e.append("Adding thread in ThreadManager failed");
    throw;
  }

  // if the thread's init() method fails, we need to finalize that very
  // thread only with the finalizer, already initialized threads muts be
  // fully finalized
  try {
    thread->init();
  } catch (CannotInitializeThreadException &e) {
    thread->notify_of_failed_init();
    __finalizer->finalize(thread);
    throw;
  } catch (Exception &e) {
    thread->notify_of_failed_init();
    CannotInitializeThreadException
      cite("Could not initialize thread '%s'", thread->name());
    cite.append(e);
    __finalizer->finalize(thread);
    throw cite;
  } catch (std::exception &e) {
    thread->notify_of_failed_init();
    CannotInitializeThreadException
      cite("Could not initialize thread '%s'", thread->name());
    cite.append("Caught std::exception or derivative: %s", e.what());
    __finalizer->finalize(thread);
    throw cite;
  } catch (...) {
    thread->notify_of_failed_init();
    CannotInitializeThreadException
      cite("Could not initialize thread '%s'", thread->name());
    cite.append("Unknown exception caught");
    __finalizer->finalize(thread);
    throw cite;
  }

  thread->start();
  MutexLocker locker(__threads.mutex(), lock);
  internal_add_thread(thread);
}
    void BvHierarchyAlgorithm::translateProxy(Proxy* proxy, const Vector3& translateBy) {
        if (!proxy) {
            throw NullPointerException("proxy");
        }

        BvHierarchyProxyData* data = static_cast<BvHierarchyProxyData*>(proxy->getDetectorDeformProxyData(getProxyDataIndex()));
        if (!data) {
            throw NullPointerException("data");
        }
        data->mDeformableNode->translate(translateBy);
    }
    void BvHierarchyAlgorithm::deformProxy(Proxy* proxy, const std::vector<Vector3>& vertexMoveArray) {
        if (!proxy) {
            throw NullPointerException("proxy");
        }

        BvHierarchyProxyData* data = static_cast<BvHierarchyProxyData*>(proxy->getDetectorDeformProxyData(getProxyDataIndex()));
        if (!data) {
            throw NullPointerException("data");
        }

        DCOLLIDE_UNUSED(vertexMoveArray);
        data->mDeformableNode->deform(/*vertexMoveArray*/);
    }
    void BvHierarchyAlgorithm::setProxyMatrix(Proxy* proxy, const Matrix& newMatrix) {
         if (!proxy) {
            throw NullPointerException("proxy");
        }

        BvHierarchyProxyData* data = static_cast<BvHierarchyProxyData*>(proxy->getDetectorDeformProxyData(getProxyDataIndex()));
        if (!data) {
            throw NullPointerException("data");
        }

        DCOLLIDE_UNUSED(newMatrix);
        data->mDeformableNode->changeMatrix(/*newMatrix*/);
   }
    void BvHierarchyAlgorithm::rotateProxy(Proxy* proxy, const Matrix& rotation) {
        if (!proxy) {
            throw NullPointerException("proxy");
        }

        BvHierarchyProxyData* data = static_cast<BvHierarchyProxyData*>(proxy->getDetectorDeformProxyData(getProxyDataIndex()));
        if (!data) {
            throw NullPointerException("data");
        }

        DCOLLIDE_UNUSED(rotation);
        data->mDeformableNode->rotate(/*rotation*/);
    }
Exemplo n.º 8
0
 /*!
  * Create \ref PipelineThreadJobCollection object that uses \p
  * pipeline nd starts its jobs in \p phase (see \ref Pipeline::Phase).
  */
 PipelineThreadJobCollection::PipelineThreadJobCollection(Pipeline* pipeline, Pipeline::Phase phase) {
     mPipeline = pipeline;
     if (!mPipeline) {
         throw NullPointerException("mPipeline");
     }
     mPhase = phase;
 }
Exemplo n.º 9
0
/** Remove the given thread.
 * The thread manager tries to finalize and stop the thread and then removes the
 * thread from the internal structures.
 *
 * This may fail if the thread cannot be finalized, for
 * example if prepare_finalize() returns false or if the thread finalizer cannot
 * finalize the thread. In this case a CannotFinalizeThreadException is thrown.
 *
 * @param thread thread to remove.
 * @exception CannotFinalizeThreadException At least one thread cannot be safely
 * finalized
 */
void
ThreadManager::remove_maybelocked(Thread *thread, bool lock)
{
  if ( thread == NULL ) return;

  if ( ! (__initializer && __finalizer) ) {
    throw NullPointerException("ThreadManager: initializer/finalizer not set");
  }

  MutexLocker locker(__threads.mutex(), lock);
  try {
    if ( ! thread->prepare_finalize() ) {
      thread->cancel_finalize();
      throw CannotFinalizeThreadException("Thread '%s'cannot be finalized", thread->name());
    }
  } catch (CannotFinalizeThreadException &e) {
    e.append("ThreadManager cannot stop thread '%s'", thread->name());
    thread->cancel_finalize();
    throw;
  }

  thread->cancel();
  thread->join();
  __finalizer->finalize(thread);
  thread->finalize();

  internal_remove_thread(thread);
}
Exemplo n.º 10
0
/** Add threads.
 * Add the given threads to the thread manager. The threads are initialised
 * as appropriate and started. See the class documentation for supported
 * specialisations of threads and the performed initialisation steps.
 * If the thread initializer cannot initalize one or more threads no thread
 * is added. In this regard the operation is atomic, either all threads are
 * added or none.
 * @param tl thread list with threads to add
 * @exception CannotInitializeThreadException thrown if at least one of the
 * threads could not be initialised
 */
void
ThreadManager::add_maybelocked(ThreadList &tl, bool lock)
{
  if ( ! (__initializer && __finalizer) ) {
    throw NullPointerException("ThreadManager: initializer/finalizer not set");
  }

  if ( tl.sealed() ) {
    throw Exception("Not accepting new threads from list that is not fresh, "
		    "list '%s' already sealed", tl.name());
  }

  tl.lock();

  // Try to initialise all threads
  try {
    tl.init(__initializer, __finalizer);
  } catch (Exception &e) {
    tl.unlock();
    throw;
  }

  tl.seal();
  tl.start();

  // All thread initialized, now add threads to internal structure
  MutexLocker locker(__threads.mutex(), lock);
  for (ThreadList::iterator i = tl.begin(); i != tl.end(); ++i) {
    internal_add_thread(*i);
  }

  tl.unlock();
}
Exemplo n.º 11
0
/** Run dialog and try to connect.
 * This runs the service chooser dialog and connects to the given service
 * with the attached FawkesNetworkClient. If the connection couldn't be established
 * an error dialog is shown. You should not rely on the connection to be
 * active after calling this method, rather you should use a ConnectionDispatcher
 * to get the "connected" signal.
 */
void
ServiceChooserDialog::run_and_connect()
{
  if (! __client)  throw NullPointerException("FawkesNetworkClient not set");
  if (__client->connected()) throw Exception("Client is already connected");

  if ( run() ) {
    try {
      Glib::ustring name;
      Glib::ustring hostname;
      Glib::ustring ipaddr;
      unsigned short int port;
      get_selected_service(name, hostname, ipaddr, port);
      if ( port == 0 )  port = 1910;

      __client->connect(hostname.c_str(), ipaddr.c_str(), port);
    } catch (Exception &e) {
      Glib::ustring message = *(e.begin());
      Gtk::MessageDialog md(__parent, message, /* markup */ false,
			    Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK,
			    /* modal */ true);
      md.set_title("Connection failed");
      md.run();
    }
  }
}
Exemplo n.º 12
0
//==============================================================================
BufferedOutputStream::BufferedOutputStream(OutputStream* pOutputStream, size_t bufSize) :
	m_rpOutputStream(pOutputStream)
{
	if(!pOutputStream) throw NullPointerException();

	init(bufSize ? bufSize : DefaultBufferSize);
}
Exemplo n.º 13
0
 /*!
  * \brief Create a new BoundingVolume object.
  *
  * This method creates and returns a new BoundingVolume object, according to
  * the preferred BoundingVolume-type settings.
  *
  * \param parent The BvhNode that the BoundingVolume should be in. See \ref
  * setHierarchyNode.
  *
  * \return A new BoundingVolume object. The caller is responsible for
  * deleting it.
  */
 BoundingVolume* BoundingVolume::createBoundingVolume(World* world, BvhNode* parent) {
     if (!world) {
         throw NullPointerException("Parameter world");
     }
     BoundingVolume* bv = 0;
     switch (getCreateRigidBoundingVolumeType(world)) {
         case BV_TYPE_AABB:
             bv = new Aabb();
             break;
         case BV_TYPE_KDOP:
             bv = new Kdop();
             break;
         case BV_TYPE_SPHERE:
             bv = new BoundingSphere();
             break;
         case BV_TYPE_OBB:
             bv = new Obb();
             break;
         default:
             // TODO: exception!!
             std::cerr << dc_funcinfo << "FATAL ERROR: bounding volume type " << getCreateRigidBoundingVolumeType(world) << " not supported" << std::endl;
             exit(1);
             return 0;
     }
     bv->setHierarchyNode(parent);
     return bv;
 }
Exemplo n.º 14
0
    /*!
     * Add \p job to the \ref ThreadPool, see \ref setPool.
     *
     * This method is NOT thread safe and assumes that it will always be called
     * from the main thread only.
     */
    void ThreadJobCollection::startJob(ThreadJob* job) {
        if (!mThreadPool) {
            throw NullPointerException("mThreadPool");
        }

        mThreadPool->addJob(job);
    }
Exemplo n.º 15
0
void Expression::addOperator(OperationCode *opcode, Token *token) {
	if (!token) {
		throw NullPointerException("Token cannot be nil");
	}

	if ((token->aType & Token::OPERATOR) == 0) {
		throw InvalidTokenException("Expected an operator, got: " + token->token);
	}

	byte oper = 0;
	string s = token->token;

	if (s == "+") {
		oper = OP_ADD;
	} else if (s == "-") {
		oper = OP_SUB;
	} else if (s == "*") {
		oper = OP_MUL;
	} else if (s == "/") {
		oper = OP_DIV;
	} else if (s == "%") {
		oper = OP_MOD;
	} else {
		throw NotImplementedException("Operator is not implemented: " + s);
	}

	opcode->addInterop(new ByteOperation(oper));
}
Exemplo n.º 16
0
//==============================================================================
BufferedOutputStream::BufferedOutputStream(OutputStream* pOutputStream) :
	m_rpOutputStream(pOutputStream)
{
	if(!pOutputStream) throw NullPointerException();

	init(DefaultBufferSize);
}
Exemplo n.º 17
0
//==============================================================================
// SystemUtils::TestBufferIsValid
//
// Test that the passed buffer is appropriate for calls to read() operations.
//==============================================================================
void SystemUtils::TestBufferIsValid(const void* pBuffer, size_t& bufLen)
{
	if(!pBuffer) throw NullPointerException();
	if(!bufLen)  throw IllegalArgumentException(QC_T("zero buffer length"));
	if(bufLen > LONG_MAX)
		bufLen = LONG_MAX;
}
Exemplo n.º 18
0
//==============================================================================
void BufferedOutputStream::write(const Byte* pBuffer, size_t bufLen)
{
	if(!pBuffer) throw NullPointerException();
	if(!m_rpOutputStream) throw IOException(QC_T("stream closed"));

	if(m_used + bufLen > m_bufferSize)
	{
		QC_DBG_ASSERT(m_pBuffer!=0);
		// Write our buffer without flushing out the stream
		writeBuffer();
		QC_DBG_ASSERT(0 == m_used);
	}

	if(bufLen > m_bufferSize)
	{
		QC_DBG_ASSERT(0 == m_used);
		m_rpOutputStream->write(pBuffer, bufLen);
	}
	else
	{
		QC_DBG_ASSERT(m_pBuffer!=0);
		QC_DBG_ASSERT(bufLen + m_used <= m_bufferSize);
		::memcpy(m_pBuffer+m_used, pBuffer, bufLen);
		m_used+=bufLen;
	}
}
    void MultiInterventionEventCoordinator::DistributeInterventionsToNodes( INodeEventContext* event_context )
    {
        const json::Array & interventions_array = json::QuickInterpreter( intervention_config._json ).As<json::Array>();
        LOG_DEBUG_F( "interventions array size = %d\n", interventions_array.Size() );
        for( int idx = 0; idx < interventions_array.Size(); idx++ )
        {
            const json::Object& actualIntervention = json_cast<const json::Object&>(interventions_array[ idx ]);
            Configuration * config = Configuration::CopyFromElement( actualIntervention );
            assert( config );

            LOG_DEBUG_F( "Attempting to instantiate intervention of class %s\n",
                std::string( (*config)[ "class" ].As<json::String>() ).c_str() );

            INodeDistributableIntervention *ndi = InterventionFactory::getInstance()->CreateNDIIntervention( config );
            if( ndi == nullptr )
            {
                throw NullPointerException( __FILE__, __LINE__, __FUNCTION__, "Should have constructed a node-level intervention." );
            }
            if( ndi->Distribute( event_context, this ) )
            {
                LOG_INFO_F( "UpdateNodes() distributed '%s' intervention to node %d\n", ndi->GetName().c_str(), event_context->GetId().data );
            }
            ndi->Release();

            delete config;
            config = nullptr;
        }
    }
Exemplo n.º 20
0
/** Register BB event listener.
 * @param listener BlackBoard event listener to register
 * @param flag flags what to register for
 */
void
BlackBoard::register_listener(BlackBoardInterfaceListener *listener, ListenerRegisterFlag flag)
{
	if (!notifier_)
		throw NullPointerException("BlackBoard initialized without notifier");
	notifier_->register_listener(listener, flag);
}
Exemplo n.º 21
0
    void
    DiagnosticTreatNeg::onPatientDefault()
    {
        LOG_DEBUG_F( "Individual %d got the test but defaulted, receiving Defaulters intervention without waiting for days_to_diagnosis (actually means days_to_intervention) \n", parent->GetSuid().data );

        // Important: Use the instance method to obtain the intervention factory obj instead of static method to cross the DLL boundary
        IGlobalContext *pGC = nullptr;
        const IInterventionFactory* ifobj = nullptr;
        if (s_OK == parent->QueryInterface(GET_IID(IGlobalContext), (void**)&pGC))
        {
            ifobj = pGC->GetInterventionFactory();
        }
        if (!ifobj)
        {
            throw NullPointerException( __FILE__, __LINE__, __FUNCTION__, "parent->GetInterventionFactoryObj()" );
        }


        if( !defaulters_event.IsUninitialized() )
        {
            if( defaulters_event != NO_TRIGGER_STR )
            {
                INodeTriggeredInterventionConsumer* broadcaster = nullptr;

                if (s_OK != parent->GetEventContext()->GetNodeEventContext()->QueryInterface(GET_IID(INodeTriggeredInterventionConsumer), (void**)&broadcaster))

                {

                    throw QueryInterfaceException( __FILE__, __LINE__, __FUNCTION__, "parent->GetEventContext()->GetNodeEventContext()", "INodeTriggeredInterventionConsumer", "INodeEventContext" );
                }
                broadcaster->TriggerNodeEventObserversByString( parent->GetEventContext(), defaulters_event );
            }
        }
        else if( defaulters_config._json.Type() != ElementType::NULL_ELEMENT )
        {
            auto tmp_config = Configuration::CopyFromElement(defaulters_config._json);

            // Distribute the defaulters intervention, right away (do not use the days_to_diagnosis
            IDistributableIntervention *di = const_cast<IInterventionFactory*>(ifobj)->CreateIntervention( tmp_config );

            delete tmp_config;
            tmp_config = nullptr;

            ICampaignCostObserver* pICCO;
            // Now make sure cost of the test-positive intervention is reported back to node
            if (s_OK == parent->GetEventContext()->GetNodeEventContext()->QueryInterface(GET_IID(ICampaignCostObserver), (void**)&pICCO) )
            {
                di->Distribute( parent->GetInterventionsContext(), pICCO );
                pICCO->notifyCampaignEventOccurred( (IBaseIntervention*)di, (IBaseIntervention*)this, parent );
            }
            else
            {
                throw QueryInterfaceException( __FILE__, __LINE__, __FUNCTION__, "parent->GetEventContext()->GetNodeEventContext()", "ICampaignCostObserver", "INodeEventContext" );
            }
        }
        else
        {
            throw GeneralConfigurationException( __FILE__, __LINE__, __FUNCTION__, "neither event or config defined" );
        }
    }
Exemplo n.º 22
0
void vmtkImageFeature::BuildFWHMBasedFeatureImage(vtkImageData*originalData,vtkImageData* res)
{
	    log4cpp::Category& rootLog  = log4cpp::Category::getRoot();
	    log4cpp::Category& subLog = log4cpp::Category::getInstance(std::string("sub1")); 
		if(res == 0||res->GetReferenceCount() < 1)
		{
			throw NullPointerException("BuildFWHMBasedFeatureImage(vtkImageData*originalData,vtkImageData* res):res是空指针,请初始化");
		}
		rootLog.info("void vmtkImageFeature::BuildFWHMBasedFeatureImage(vtkImageData*originalData,vtkImageData* res) start......");
		subLog.info("void vmtkImageFeature::BuildFWHMBasedFeatureImage(vtkImageData*originalData,vtkImageData* res) start.......");
		vtkSmartPointer<vtkImageCast> cast = vtkSmartPointer<vtkImageCast>::New();        
		cast->SetInputData(originalData);
        cast->SetOutputScalarTypeToFloat();
        cast->Update();
		
		vtkSmartPointer<vtkvmtkFWHMFeatureImageFilter> fwhmFeatureImageFilter = vtkSmartPointer<vtkvmtkFWHMFeatureImageFilter>::New();
        //fwhmFeatureImageFilter->SetInputConnection(cast->GetOutputPort());
		fwhmFeatureImageFilter->SetInputData(cast->GetOutput());
		int _FWHMRadius[3];
		for(int i = 0; i < 3;i++)
		{
			_FWHMRadius[i] = FWHMRadius[i];
		}
        fwhmFeatureImageFilter->SetRadius(_FWHMRadius);
        fwhmFeatureImageFilter->SetBackgroundValue(FWHMBackgroundValue);
        fwhmFeatureImageFilter->Update();
	
		res->DeepCopy(fwhmFeatureImageFilter->GetOutput());
}
Exemplo n.º 23
0
/** Unregister BB interface observer.
 * This will remove the given BlackBoard event listener from any event that it was
 * previously registered for.
 * @param observer BlackBoard event listener to remove
 */
void
BlackBoard::unregister_observer(BlackBoardInterfaceObserver *observer)
{
    if (! __notifier) throw NullPointerException("BlackBoard initialized without notifier");
    if (! observer) return;
    __notifier->unregister_observer(observer);
}
Exemplo n.º 24
0
/** Unregister BB interface listener.
 * This will remove the given BlackBoard interface listener from any
 * event that it was previously registered for.
 * @param listener BlackBoard event listener to remove
 */
void
BlackBoard::unregister_listener(BlackBoardInterfaceListener *listener)
{
    if (! __notifier) throw NullPointerException("BlackBoard initialized without notifier");
    if (! listener) return;
    __notifier->unregister_listener(listener);
}
Exemplo n.º 25
0
    /*!
     * \brief adjusts this bounding volume to an given shape
     *        (top-down processing)
     */
    void BoundingVolume::adjustToShape(const Shape* shape) {
        if (!shape) {
            throw NullPointerException("Parameter \"const Shape* shape\"");
        }
        if (!shape->getProxy()) {
            throw NullPointerException("shape->getProxy()");
        }
        Matrix worldState(shape->getProxy()->getWorldTransformation());
        switch(shape->getShapeType()) {
            case Shape::SHAPE_TYPE_BOX:
                    adjustToBox(&worldState,
                                 static_cast<const Box*>(shape));
                    break;

            case Shape::SHAPE_TYPE_CONE:
                    adjustToCone(&worldState,
                                  static_cast<const Cone*>(shape));
                    break;

            case Shape::SHAPE_TYPE_CYLINDER:
                    adjustToCylinder(&worldState,
                                      static_cast<const Cylinder*>(shape));
                    break;

            case Shape::SHAPE_TYPE_MESH:
                    adjustToMesh(static_cast<const Mesh*>(shape));
                    break;

            case Shape::SHAPE_TYPE_MESH_PART:
                    adjustToMeshPart(static_cast<const MeshPart*>(shape));
                    break;

            case Shape::SHAPE_TYPE_SPHERE:
                    adjustToSphere(&worldState,
                                    static_cast<const Sphere*>(shape));
                    break;

            case Shape::SHAPE_TYPE_WEDGE:
                    adjustToWedge(&worldState,
                                   static_cast<const Wedge*>(shape));
                    break;

            default:
                    throw UnsupportedShapeException(
                        "Cannot adjust Aabb to unknown Shape");
        }
    }
Exemplo n.º 26
0
/** Wakeup threads and wait for them to finish.
 * This assumes that all threads are in wait-for-wakeup mode. The threads are woken
 * up with an internally maintained barrier. The method will return when all threads
 * have finished one loop() iteration.
 * @param timeout_sec timeout in seconds
 * @param timeout_nanosec timeout in nanoseconds
 * @exception NullPointerException thrown, if no internal barrier is maintained. Make sure
 * you use the proper constructor.
 */
void
ThreadList::wakeup_and_wait(unsigned int timeout_sec, unsigned int timeout_nanosec)
{
  if ( ! __wnw_barrier ) {
    throw NullPointerException("ThreadList::wakeup_and_wait() can only be called if "
			       "barrier is maintained");
  }

  MutexLocker lock(mutex());

  try {
    wakeup_unlocked(__wnw_barrier);
  } catch (Exception &e) {
    throw;
  }
  if ( ! __wnw_barrier->wait(timeout_sec, timeout_nanosec) ) {
    // timeout, we have a bad thread, flag it
    RefPtr<ThreadList> passed_threads = __wnw_barrier->passed_threads();
    ThreadList bad_threads;
    for (iterator i = begin(); i != end(); ++i) {
      if ((*i)->flagged_bad()) {
        // thread is already flagged as bad, don't add it to bad_threads
        continue;
      }
      bool ok = false;
      for (iterator j = passed_threads->begin(); j != passed_threads->end(); ++j) {
	if (*j == *i) {
	  ok = true;
	  break;
	}
      }
      if (! ok) {
	bad_threads.push_back(*i);
	(*i)->set_flag(Thread::FLAG_BAD);
      }
    }

    __wnw_bad_barriers.push_back(make_pair(__wnw_barrier, bad_threads));

    __wnw_barrier = NULL;
    update_barrier();

    // Formulate exception
    std::string s;
    if ( bad_threads.size() > 1 ) {
      s = "Multiple threads did not finish in time, flagging as bad: ";
      for (iterator i = bad_threads.begin(); i != bad_threads.end(); ++i) {
	s += std::string((*i)->name()) + " ";
      }
    } else if (bad_threads.size() == 0) {
      s = "Timeout happened, but no bad threads recorded.";
    } else {
      throw Exception("Thread %s did not finish in time (max %f), flagging as bad",
		      bad_threads.front()->name(),
		      (float)timeout_sec + (float)timeout_nanosec / 1000000000.);
    }
    throw Exception("%s", s.c_str());
  }
}
Exemplo n.º 27
0
//==============================================================================
BufferedWriter::BufferedWriter(Writer* pWriter, size_t bufSize) :
	m_rpWriter(pWriter)
{
	if(!pWriter) throw NullPointerException();
	m_rpLock = pWriter->getLock();

	init(bufSize ? bufSize : DefaultBufferSize);
}
Exemplo n.º 28
0
void Group::AddObserver(INotifiableSystem* pObserver)
{
	if(!pObserver){
		throw NullPointerException("Group::AddObserver", "Observer is null");
	}

	m_pObservers.push_back(pObserver);
}
Exemplo n.º 29
0
/** Update BB event listener.
 * @param listener BlackBoard event listener to update
 * @param flag flags what to update for
 */
void
BlackBoard::update_listener(BlackBoardInterfaceListener *listener,
                            ListenerRegisterFlag flag)
{
    if (! __notifier) throw NullPointerException("BlackBoard initialized without notifier");
    if (! listener)  return;
    __notifier->update_listener(listener, flag);
}
Exemplo n.º 30
0
/** Return payload size
 * @return payload size
 * @exception NullPointerException thrown if _payload does not point to a valid
 * buffer or if _payload_size is zero.
 */
size_t
FawkesNetworkMessageContent::payload_size()
{
  if ( (_payload == NULL) || (_payload_size == 0) ) {
    throw NullPointerException("Payload in network message content may not be NULL");
  }
  return _payload_size;
}