Пример #1
25
u32 TextureSource::getTextureId(const std::string &name)
{
	//infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;

	{
		/*
			See if texture already exists
		*/
		JMutexAutoLock lock(m_textureinfo_cache_mutex);
		std::map<std::string, u32>::iterator n;
		n = m_name_to_id.find(name);
		if(n != m_name_to_id.end())
		{
			return n->second;
		}
	}

	/*
		Get texture
	*/
	if(get_current_thread_id() == m_main_thread)
	{
		return getTextureIdDirect(name);
	}
	else
	{
		infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;

		// We're gonna ask the result to be put into here
		static ResultQueue<std::string, u32, u8, u8> result_queue;

		// Throw a request in
		m_get_texture_queue.add(name, 0, 0, &result_queue);

		/*infostream<<"Waiting for texture from main thread, name=\""
				<<name<<"\""<<std::endl;*/

		try
		{
			while(true) {
				// Wait result for a second
				GetResult<std::string, u32, u8, u8>
					result = result_queue.pop_front(1000);

				if (result.key == name) {
					return result.item;
				}
			}
		}
		catch(ItemNotFoundException &e)
		{
			errorstream<<"Waiting for texture " << name << " timed out."<<std::endl;
			return 0;
		}
	}

	infostream<<"getTextureId(): Failed"<<std::endl;

	return 0;
}
Пример #2
0
void Loader::Host::servePendingRequests(RequestQueue& requestsPending)
{
    while (m_requestsLoading.size() < m_maxRequestsInFlight && !requestsPending.isEmpty()) {        
        Request* request = requestsPending.first();
        requestsPending.removeFirst();

        DocLoader* docLoader = request->docLoader();
        
        ResourceRequest resourceRequest(request->cachedResource()->url());
        
        if (!request->cachedResource()->accept().isEmpty())
            resourceRequest.setHTTPAccept(request->cachedResource()->accept());
        
        KURL referrer = docLoader->doc()->url();
        if ((referrer.protocolIs("http") || referrer.protocolIs("https")) && referrer.path().isEmpty())
            referrer.setPath("/");
        resourceRequest.setHTTPReferrer(referrer.string());

        RefPtr<SubresourceLoader> loader = SubresourceLoader::create(docLoader->doc()->frame(),
                                                                     this, resourceRequest, request->shouldSkipCanLoadCheck(), request->sendResourceLoadCallbacks());
        if (loader) {
            m_requestsLoading.add(loader.release(), request);
            request->cachedResource()->setRequestedFromNetworkingLayer();
#if REQUEST_DEBUG
            printf("HOST %s COUNT %d LOADING %s\n", resourceRequest.url().host().latin1().data(), m_requestsLoading.size(), request->cachedResource()->url().latin1().data());
#endif
        } else {            
            docLoader->decrementRequestCount();
            docLoader->setLoadInProgress(true);
            request->cachedResource()->error();
            docLoader->setLoadInProgress(false);
            delete request;
        }
    }
}
uint32_t LocationAPIClientBase::locAPIStartTracking(LocationOptions& options)
{
    uint32_t retVal = LOCATION_ERROR_GENERAL_FAILURE;
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        if (mTracking) {
            LOC_LOGW("%s:%d] Existing tracking session present", __FUNCTION__, __LINE__);
        } else {
            RequestQueue* requests = mRequestQueues[REQUEST_TRACKING];
            if (requests) {
                delete requests;
                mRequestQueues[REQUEST_TRACKING] = nullptr;
            }
            uint32_t session = mLocationAPI->startTracking(options);
            LOC_LOGI("%s:%d] start new session: %d", __FUNCTION__, __LINE__, session);
            // onResponseCb might be called from other thread immediately after
            // startTracking returns, so we are not going to unlock mutex
            // until StartTrackingRequest is pushed into mRequestQueues[REQUEST_TRACKING]
            requests = new RequestQueue(session);
            requests->push(new StartTrackingRequest(*this));
            mRequestQueues[REQUEST_TRACKING] = requests;
            mTracking = true;
        }
        retVal = LOCATION_ERROR_SUCCESS;
    }
    pthread_mutex_unlock(&mMutex);

    return retVal;
}
void LocationAPIClientBase::locAPIResumeGeofences(
        size_t count, uint32_t* ids, GeofenceBreachTypeMask* mask)
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        uint32_t* sessions = (uint32_t*)malloc(sizeof(uint32_t) * count);

        RequestQueue* requests = mRequestQueues[REQUEST_GEOFENCE];
        if (requests) {
            size_t j = 0;
            for (size_t i = 0; i < count; i++) {
                sessions[j] = mGeofenceBiDict.getSession(ids[i]);
                if (sessions[j] > 0) {
                    if (mask) {
                        mGeofenceBiDict.set(ids[i], sessions[j], mask[i]);
                    }
                    j++;
                }
            }
            if (j > 0) {
                requests->push(new ResumeGeofencesRequest(*this));
                mLocationAPI->resumeGeofences(j, sessions);
            }
        }

        free(sessions);
    }
    pthread_mutex_unlock(&mMutex);
}
void LocationAPIClientBase::locAPIRemoveAllGeofences()
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        std::vector<uint32_t> sessionsVec = mGeofenceBiDict.getAllSessions();
        size_t count = sessionsVec.size();
        uint32_t* sessions = (uint32_t*)malloc(sizeof(uint32_t) * count);

        RequestQueue* requests = mRequestQueues[REQUEST_GEOFENCE];
        if (requests) {
            size_t j = 0;
            for (size_t i = 0; i < count; i++) {
                sessions[j] = sessionsVec[i];
                if (sessions[j] > 0) {
                    j++;
                }
            }
            if (j > 0) {
                requests->push(new RemoveGeofencesRequest(*this));
                mLocationAPI->removeGeofences(j, sessions);
            }
        }

        free(sessions);
    }
    pthread_mutex_unlock(&mMutex);
}
uint32_t LocationAPIClientBase::locAPIAddGeofences(
        size_t count, uint32_t* ids, GeofenceOption* options, GeofenceInfo* data)
{
    uint32_t retVal = LOCATION_ERROR_GENERAL_FAILURE;
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        RequestQueue* requests = mRequestQueues[REQUEST_GEOFENCE];
        if (!requests) {
            // Create a new RequestQueue for Geofenceing if we've not had one.
            // The RequestQueue will be released when LocationAPIClientBase is released.
            requests = new RequestQueue(GEOFENCE_SESSION_ID);
            mRequestQueues[REQUEST_GEOFENCE] = requests;
        }
        uint32_t* sessions = mLocationAPI->addGeofences(count, options, data);
        if (sessions) {
            LOC_LOGI("%s:%d] start new sessions: %p", __FUNCTION__, __LINE__, sessions);
            requests->push(new AddGeofencesRequest(*this));

            for (size_t i = 0; i < count; i++) {
                mGeofenceBiDict.set(ids[i], sessions[i], options[i].breachTypeMask);
            }
            retVal = LOCATION_ERROR_SUCCESS;
        }
    }
    pthread_mutex_unlock(&mMutex);

    return retVal;
}
Пример #7
0
void Loader::Host::servePendingRequests(RequestQueue& requestsPending, bool& serveLowerPriority)
{
    while (!requestsPending.isEmpty()) {        
        Request* request = requestsPending.first();
        DocLoader* docLoader = request->docLoader();
        bool resourceIsCacheValidator = request->cachedResource()->isCacheValidator();

        // For named hosts - which are only http(s) hosts - we should always enforce the connection limit.
        // For non-named hosts - everything but http(s) - we should only enforce the limit if the document isn't done parsing 
        // and we don't know all stylesheets yet.
        bool shouldLimitRequests = !m_name.isNull() || docLoader->doc()->parsing() || !docLoader->doc()->haveStylesheetsLoaded();
        if (shouldLimitRequests && m_requestsLoading.size() + m_nonCachedRequestsInFlight >= m_maxRequestsInFlight) {
            serveLowerPriority = false;
            cache()->loader()->scheduleServePendingRequests();
            return;
        }
        requestsPending.removeFirst();
        
        ResourceRequest resourceRequest(request->cachedResource()->url());
        resourceRequest.setTargetType(cachedResourceTypeToTargetType(request->cachedResource()->type()));
        
        if (!request->cachedResource()->accept().isEmpty())
            resourceRequest.setHTTPAccept(request->cachedResource()->accept());
        
         // Do not set the referrer or HTTP origin here. That's handled by SubresourceLoader::create.
        
        if (resourceIsCacheValidator) {
            CachedResource* resourceToRevalidate = request->cachedResource()->resourceToRevalidate();
            ASSERT(resourceToRevalidate->canUseCacheValidator());
            ASSERT(resourceToRevalidate->isLoaded());
            const String& lastModified = resourceToRevalidate->response().httpHeaderField("Last-Modified");
            const String& eTag = resourceToRevalidate->response().httpHeaderField("ETag");
            if (!lastModified.isEmpty() || !eTag.isEmpty()) {
                ASSERT(docLoader->cachePolicy() != CachePolicyReload);
                if (docLoader->cachePolicy() == CachePolicyRevalidate)
                    resourceRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
                if (!lastModified.isEmpty())
                    resourceRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
                if (!eTag.isEmpty())
                    resourceRequest.setHTTPHeaderField("If-None-Match", eTag);
            }
        }

        RefPtr<SubresourceLoader> loader = SubresourceLoader::create(docLoader->doc()->frame(),
            this, resourceRequest, request->shouldDoSecurityCheck(), request->sendResourceLoadCallbacks());
        if (loader) {
            m_requestsLoading.add(loader.release(), request);
            request->cachedResource()->setRequestedFromNetworkingLayer();
#if REQUEST_DEBUG
            printf("HOST %s COUNT %d LOADING %s\n", resourceRequest.url().host().latin1().data(), m_requestsLoading.size(), request->cachedResource()->url().latin1().data());
#endif
        } else {            
            docLoader->decrementRequestCount();
            docLoader->setLoadInProgress(true);
            request->cachedResource()->error();
            docLoader->setLoadInProgress(false);
            delete request;
        }
    }
}
Пример #8
0
void
RequestQueueTest::queueLockTest()
{
    RequestQueue* queue = new RequestQueue();
    pthread_mutex_t thread_mutex;
    struct timespec timeout;

    pthread_mutex_init(&thread_mutex, NULL);

    // mutex should be locked
    queue->queueLock(&thread_mutex);

    clock_gettime(CLOCK_REALTIME, &timeout);
    int result = pthread_mutex_timedlock(&thread_mutex, &timeout);

    CPPUNIT_ASSERT(result != 0);

    queueItem* item = new queueItem();
    item->methodId = 1;

    queue->addItem(0, item);

    // mutex should be unlocked
    clock_gettime(CLOCK_REALTIME, &timeout);
    result = pthread_mutex_timedlock(&thread_mutex, &timeout);

    CPPUNIT_ASSERT(result == 0);
}
uint32_t LocationAPIClientBase::locAPIGnssUpdateConfig(GnssConfig config)
{
    uint32_t retVal = LOCATION_ERROR_GENERAL_FAILURE;
    if (memcmp(&mConfig, &config, sizeof(GnssConfig)) == 0) {
        LOC_LOGV("%s:%d] GnssConfig is identical to previous call", __FUNCTION__, __LINE__);
        retVal = LOCATION_ERROR_SUCCESS;
        return retVal;
    }

    pthread_mutex_lock(&mMutex);
    if (mLocationControlAPI) {

        memcpy(&mConfig, &config, sizeof(GnssConfig));

        uint32_t session = 0;
        RequestQueue* requests = mRequestQueues[REQUEST_CONFIG];
        uint32_t* idArray = mLocationControlAPI->gnssUpdateConfig(config);
        LOC_LOGV("%s:%d] gnssUpdateConfig return array: %p", __FUNCTION__, __LINE__, idArray);
        if (!requests && idArray != nullptr) {
            requests = new RequestQueue(idArray[0]);
            mRequestQueues[REQUEST_CONFIG] = requests;
        }
        if (requests) {
            requests->push(new GnssUpdateConfigRequest(*this));
            retVal = LOCATION_ERROR_SUCCESS;
        }
    }
    pthread_mutex_unlock(&mMutex);
    return retVal;
}
Пример #10
0
unsigned int RequestQueue::WorkerThread(void *arg)
{
	RequestQueue *queue = (RequestQueue*)arg;

	while (!queue->isTerminated)
	{
		WaitForSingleObject(queue->hRequestQueueEvent, INFINITE);
		while (true)
		{
			RequestQueueItem *item = NULL;
			{
				mir_cslock lock(queue->requestQueueLock);

				if (queue->requests.getCount() == 0)
					break;

				item = queue->requests[0];
				queue->requests.remove(0);
			}
			if (item != NULL)
				queue->Execute(item);
		}
	}

	queue->hRequestQueueThread = NULL;
	return 0;
}
uint32_t LocationAPIClientBase::locAPIEnable(LocationTechnologyType techType)
{
    uint32_t retVal = LOCATION_ERROR_GENERAL_FAILURE;
    pthread_mutex_lock(&mMutex);
    if (mEnabled) {
        // just return success if already enabled
        retVal = LOCATION_ERROR_SUCCESS;
    } else if (mLocationControlAPI) {
        RequestQueue* requests = mRequestQueues[REQUEST_CONTROL];
        if (requests) {
            delete requests;
            mRequestQueues[REQUEST_CONTROL] = nullptr;
        }
        uint32_t session = mLocationControlAPI->enable(techType);
        LOC_LOGI("%s:%d] start new session: %d", __FUNCTION__, __LINE__, session);
        requests = new RequestQueue(session);
        mRequestQueues[REQUEST_CONTROL] = requests;
        if (requests) {
            requests->push(new EnableRequest(*this));
            retVal = LOCATION_ERROR_SUCCESS;
            mEnabled = true;
        }
    }
    pthread_mutex_unlock(&mMutex);

    return retVal;
}
Пример #12
0
void
MessageProcessorTest::processPendingItemsTest()
{
    ExampleClass* example = new ExampleClass();
    MessageProcessor<ExampleClass>* processor =
        new MessageProcessor<ExampleClass>(example,
                                           &ExampleClass::innerCallbackFunction);

    processor->setMethodCallback(1,
                                 &ExampleClass::innerCallbackFunctionTwo);
    Client* client = new Client(1);
    processor->setClient(client);

    pthread_t serverThread;
    RequestQueue* iqueue = new RequestQueue();
    RequestQueue* oqueue = new RequestQueue();
    RequestQueue* imqueue = new RequestQueue();

    shared_ptr<LocalRequestManagerHandler> handler
        (new LocalRequestManagerHandler(iqueue, oqueue, imqueue));
    shared_ptr<TProcessor> serverProcessor
        (new LocalRequestManagerProcessor(handler));
    shared_ptr<TServerTransport> transport(new TServerSocket(9191));
    shared_ptr<TTransportFactory> transportFactory
        (new TBufferedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

    TSimpleServer *testServer = new TSimpleServer(serverProcessor,
                                                  transport,
                                                  transportFactory,
                                                  protocolFactory);

    pthread_create(&serverThread, NULL, runServer, (void*) testServer);
    sleep(2);

    client->connect();

    queueItem item_one;
    queueItem item_two;
    item_one.methodId = 1;
    item_two.methodId = 1;
    
    iqueue->addItem(1, &item_one);
    iqueue->addItem(1, &item_two);
    
    processor->processPendingItems(-1);

    CPPUNIT_ASSERT(client != NULL &&
                   testServer != NULL &&
                   processor != NULL);

    client->disconnect();

    testServer->stop();
    sleep(2);

    delete testServer;
}
Пример #13
0
void
KumonosuManagerTest::pingTest()
{
    pthread_t serverThread;
    RequestQueue* iqueue = new RequestQueue();
    RequestQueue* oqueue = new RequestQueue();
    RequestQueue* imqueue = new RequestQueue();

    shared_ptr<LocalRequestManagerHandler> handler
        (new LocalRequestManagerHandler(iqueue, oqueue, imqueue));
    shared_ptr<TProcessor> serverProcessor
        (new LocalRequestManagerProcessor(handler));
    shared_ptr<TServerTransport> transport(new TServerSocket(9393));
    shared_ptr<TTransportFactory> transportFactory
        (new TBufferedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

    TSimpleServer *testServer = new TSimpleServer(serverProcessor,
                                                  transport,
                                                  transportFactory,
                                                  protocolFactory);

    pthread_create(&serverThread, NULL, runServer, (void*) testServer);
    sleep(2);

    queueItem* item = new queueItem();
    item->methodId = ManagerMethodMap::Ping;

    ping_arguments pingItem("a.badhostname.com", 8989, 24, 0, 1);
    item->argList = (arguments) pingItem;

    iqueue->addItem(0, item);

    KumonosuManager* manager = new KumonosuManager("localhost", 9393);

    // Add the server that would correspond with the Ping response
    // above
    Server newServer;
    newServer.setServerAddress("a.badhostname.com");
    newServer.setServerPort(8989);
    newServer.setServerId(24);

    manager->addServer(newServer);

    pthread_t managerThread;

    pthread_create(&managerThread, NULL, runManager, (void*) manager);

    sleep(4);
    manager->stop();
    testServer->stop();
    CPPUNIT_ASSERT_MESSAGE("Incoming queue is not 0",
                           iqueue->getItemQueue(0).size() == 0);

    CPPUNIT_ASSERT_MESSAGE("Outgoing queue is not 1",
                           oqueue->getItemQueue(0).size() != 0);
}
Пример #14
0
unsigned int RequestQueue::AsyncSendThread(void *owner, void *arg)
{
	RequestQueue *queue = (RequestQueue*)owner;
	RequestQueueItem *item = (RequestQueueItem*)arg;

	queue->Execute(item);

	return 0;
}
Пример #15
0
void
RequestQueueTest::addItemTest()
{
    RequestQueue* queue = new RequestQueue();
    int32_t serviceId = 1;
    queueItem item;
    item.methodId = 0;
    queue->addItem(serviceId, &item);
}
Пример #16
0
void
KumonosuManagerTest::getServiceListTest()
{
    pthread_t serverThread;
    RequestQueue* iqueue = new RequestQueue();
    RequestQueue* oqueue = new RequestQueue();
    RequestQueue* imqueue = new RequestQueue();

    shared_ptr<LocalRequestManagerHandler> handler
        (new LocalRequestManagerHandler(iqueue, oqueue, imqueue));
    shared_ptr<TProcessor> serverProcessor
        (new LocalRequestManagerProcessor(handler));
    shared_ptr<TServerTransport> transport(new TServerSocket(9797));
    shared_ptr<TTransportFactory> transportFactory
        (new TBufferedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

    TSimpleServer *testServer = new TSimpleServer(serverProcessor,
                                                  transport,
                                                  transportFactory,
                                                  protocolFactory);

    pthread_create(&serverThread, NULL, runServer, (void*) testServer);
    sleep(2);

    queueItem* item = new queueItem();
    item->methodId = ManagerMethodMap::GetServiceList;
    i32Arg serverId;
    serverId.name = "serverid";
    serverId.value = 34;
    item->argList.i32Args.push_back(serverId);
    i32Arg serviceId;
    serviceId.name = "serviceid";
    serviceId.value = 0;
    item->argList.i32Args.push_back(serviceId);

    iqueue->addItem(0, item);

    KumonosuManager* manager = new KumonosuManager("localhost", 9797);

    pthread_t managerThread;

    pthread_create(&managerThread, NULL, runManager, (void*) manager);

    sleep(4);
    manager->stop();
    // getServerList should generate an outgoing message
    CPPUNIT_ASSERT_MESSAGE("Incoming queue is not 0",
                           iqueue->getItemQueue(0).size() == 0);

    CPPUNIT_ASSERT_MESSAGE("Outgoing queue is not 1",
                           oqueue->getItemQueue(0).size() == 1);

    testServer->stop();
}
uint32_t LocationAPIClientBase::locAPIStartSession(uint32_t id, uint32_t sessionMode,
        LocationOptions& options)
{
    uint32_t retVal = LOCATION_ERROR_GENERAL_FAILURE;
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {

        if (mSessionMap.find(id) != mSessionMap.end()) {
            LOC_LOGE("%s:%d] session %d has already started.", __FUNCTION__, __LINE__, id);
            retVal = LOCATION_ERROR_ALREADY_STARTED;
        } else {
            uint32_t trackingSession = 0;
            uint32_t batchingSession = 0;

            if (sessionMode == SESSION_MODE_ON_FIX) {
                RequestQueue* requests = mRequestQueues[REQUEST_TRACKING];
                if (requests) {
                    delete requests;
                    mRequestQueues[REQUEST_TRACKING] = nullptr;
                }
                trackingSession = mLocationAPI->startTracking(options);
                LOC_LOGI("%s:%d] start new session: %d", __FUNCTION__, __LINE__, trackingSession);
                requests = new RequestQueue(trackingSession);
                requests->push(new StartTrackingRequest(*this));
                mRequestQueues[REQUEST_TRACKING] = requests;
            } else if (sessionMode == SESSION_MODE_ON_FULL) {
                RequestQueue* requests = mRequestQueues[REQUEST_BATCHING];
                if (requests) {
                    delete requests;
                    mRequestQueues[REQUEST_BATCHING] = nullptr;
                }
                batchingSession = mLocationAPI->startBatching(options);
                LOC_LOGI("%s:%d] start new session: %d", __FUNCTION__, __LINE__, batchingSession);
                requests = new RequestQueue(batchingSession);
                requests->push(new StartBatchingRequest(*this));
                mRequestQueues[REQUEST_BATCHING] = requests;
            }

            SessionEntity entity;
            entity.id = id;
            entity.trackingSession = trackingSession;
            entity.batchingSession = batchingSession;
            entity.sessionMode = sessionMode;
            mSessionMap[id] = entity;

            retVal = LOCATION_ERROR_SUCCESS;
        }

    }
    pthread_mutex_unlock(&mMutex);

    return retVal;
}
Пример #18
0
void
RequestQueueTest::getItemTest()
{
    RequestQueue* queue = new RequestQueue();
    int32_t serviceId = 1;
    queueItem item;
    queueItem* resultItem;
    item.methodId = 0;
    queue->addItem(serviceId, &item);

    resultItem = queue->getItem(serviceId);
    CPPUNIT_ASSERT(resultItem->methodId == item.methodId);
}
Пример #19
0
void Loader::Host::cancelPendingRequests(RequestQueue& requestsPending, DocLoader* docLoader)
{
    RequestQueue remaining;
    RequestQueue::iterator end = requestsPending.end();
    for (RequestQueue::iterator it = requestsPending.begin(); it != end; ++it) {
        Request* request = *it;
        if (request->docLoader() == docLoader) {
            cache()->remove(request->cachedResource());
            delete request;
            docLoader->decrementRequestCount();
        } else
            remaining.append(request);
    }
    requestsPending.swap(remaining);
}
void LocationAPIClientBase::locAPIGetBatchedLocations(size_t count)
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        uint32_t session = 0;
        RequestQueue* requests = mRequestQueues[REQUEST_BATCHING];
        if (requests) {
            session = requests->getSession();
            if (session > 0) {
                requests->push(new GetBatchedLocationsRequest(*this));
                mLocationAPI->getBatchedLocations(session, count);
            }
        }
    }
    pthread_mutex_unlock(&mMutex);
}
Пример #21
0
// Note that -1 indicates a failure to copy/add, not in the source (this).
int RequestQueue::Copy(RequestQueue &dstq, bt_index_t idx) const
{
  const PIECE *piece;
  const SLICE *slice;

  if( dstq.FindPiece(idx) ) return 0;

  if( !(piece = FindPiece(idx)) ) return 0;
  for( slice = piece->slices; slice; slice = slice->next ){
    if( !dstq.Add(slice->index, slice->offset, slice->length) ){
      dstq.Delete(idx);
      return -1;
    }
  }
  return 1;
}
Пример #22
0
void* randomRequestGen(void *d)
{

	while(total_requests){
		cout << "random request gen.. " << endl;
		int service_select = rand()%6;
		string service = ServiceUrls[service_select];
		int enc_fields = ServiceFieldMap[service_select];


		stringstream sRequestStream;
		sRequestStream << (*config)["host"]  << service;

		while(enc_fields){
			cout << "service: " << service << endl;
			int field_id = enc_fields%10 - 1;
			cout << "field: " << Fields[field_id] << endl;
			string data = getRandomData(field_id);
			sRequestStream << Fields[field_id] << "=" << data << "&";
			enc_fields = enc_fields/10;
		}

		if(total_requests){
				URLS_QUEUE.addToQueue(sRequestStream.str());
				cout << "request: " << sRequestStream.str() << endl;
				total_requests--;
		}
		usleep(100);
	}
}
void LocationAPIClientBase::locAPIUpdateTrackingOptions(LocationOptions& options)
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        uint32_t session = 0;
        RequestQueue* requests = mRequestQueues[REQUEST_TRACKING];
        if (requests) {
            session = requests->getSession();
            if (session > 0) {
                requests->push(new UpdateTrackingOptionsRequest(*this));
                mLocationAPI->updateTrackingOptions(session, options);
            }
        }
    }
    pthread_mutex_unlock(&mMutex);
}
Пример #24
0
void
KumonosuManagerTest::methodNotFoundTest()
{
    // Set up the server
    pthread_t serverThread;
    RequestQueue* iqueue = new RequestQueue();
    RequestQueue* oqueue = new RequestQueue();
    RequestQueue* imqueue = new RequestQueue();

    shared_ptr<LocalRequestManagerHandler> handler
        (new LocalRequestManagerHandler(iqueue, oqueue, imqueue));
    shared_ptr<TProcessor> serverProcessor
        (new LocalRequestManagerProcessor(handler));
    shared_ptr<TServerTransport> transport(new TServerSocket(9292));
    shared_ptr<TTransportFactory> transportFactory
        (new TBufferedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

    TSimpleServer *testServer = new TSimpleServer(serverProcessor,
                                                  transport,
                                                  transportFactory,
                                                  protocolFactory);

    pthread_create(&serverThread, NULL, runServer, (void*) testServer);
    sleep(2);

    // Set up the invalid method call
    queueItem* item = new queueItem();
    item->methodId = 800;
    iqueue->addItem(0, item);

    // Create the manager
    KumonosuManager* manager = new KumonosuManager("localhost", 9292);

    // Set the manager to run, invoking the methodNotFound call
    pthread_t managerThread;

    pthread_create(&managerThread, NULL, runManager, (void*) manager);

    // Pause to let it run some
    sleep(4);
    manager->stop();
    CPPUNIT_ASSERT_MESSAGE("item queue size is not 0",
                           iqueue->getItemQueue(0).size() == 0);

    testServer->stop();
}
Пример #25
0
u32 TextureSource::getTextureId(const std::string &name)
{
	//infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;

	{
		/*
			See if texture already exists
		*/
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);
		core::map<std::string, u32>::Node *n;
		n = m_name_to_id.find(name);
		if(n != NULL)
		{
			return n->getValue();
		}
	}
	
	/*
		Get texture
	*/
	if(get_current_thread_id() == m_main_thread)
	{
		return getTextureIdDirect(name);
	}
	else
	{
		infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;

		// We're gonna ask the result to be put into here
		ResultQueue<std::string, u32, u8, u8> result_queue;
		
		// Throw a request in
		m_get_texture_queue.add(name, 0, 0, &result_queue);
		
		infostream<<"Waiting for texture from main thread, name=\""
				<<name<<"\""<<std::endl;
		
		try
		{
			// Wait result for a second
			GetResult<std::string, u32, u8, u8>
					result = result_queue.pop_front(1000);
		
			// Check that at least something worked OK
			assert(result.key == name);

			return result.item;
		}
		catch(ItemNotFoundException &e)
		{
			infostream<<"Waiting for texture timed out."<<std::endl;
			return 0;
		}
	}
	
	infostream<<"getTextureId(): Failed"<<std::endl;

	return 0;
}
void LocationAPIClientBase::locAPIDisable()
{
    pthread_mutex_lock(&mMutex);
    if (mEnabled && mLocationControlAPI) {
        uint32_t session = 0;
        RequestQueue* requests = mRequestQueues[REQUEST_CONTROL];
        if (requests) {
            session = requests->getSession();
            if (session > 0) {
                requests->push(new DisableRequest(*this));
                mLocationControlAPI->disable(session);
                mEnabled = false;
            }
        }
    }
    pthread_mutex_unlock(&mMutex);
}
void LocationAPIClientBase::locAPIStopTracking()
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        uint32_t session = 0;
        RequestQueue* requests = mRequestQueues[REQUEST_TRACKING];
        if (requests) {
            session = requests->getSession();
            if (session > 0) {
                requests->push(new StopTrackingRequest(*this));
                mLocationAPI->stopTracking(session);
                mTracking = false;
            }
        }
    }
    pthread_mutex_unlock(&mMutex);
}
void LocationAPIClientBase::locAPIGnssNiResponse(uint32_t id, GnssNiResponse response)
{
    pthread_mutex_lock(&mMutex);
    if (mLocationAPI) {
        RequestQueue* requests = mRequestQueues[REQUEST_NIRESPONSE];
        if (requests) {
            delete requests;
            mRequestQueues[REQUEST_NIRESPONSE] = nullptr;
        }
        uint32_t session = id;
        mLocationAPI->gnssNiResponse(id, response);
        LOC_LOGI("%s:%d] start new session: %d", __FUNCTION__, __LINE__, session);
        requests = new RequestQueue(session);
        requests->push(new GnssNiResponseRequest(*this));
        mRequestQueues[REQUEST_NIRESPONSE] = requests;
    }
    pthread_mutex_unlock(&mMutex);
}
Пример #29
0
void ShaderSource::processQueue()
{
	/*
		Fetch shaders
	*/
	//NOTE this is only thread safe for ONE consumer thread!
	if(!m_get_shader_queue.empty()){
		GetRequest<std::string, u32, u8, u8>
				request = m_get_shader_queue.pop();

		/**errorstream<<"ShaderSource::processQueue(): "
				<<"got shader request with "
				<<"name=\""<<request.key<<"\""
				<<std::endl;**/

		m_get_shader_queue.pushResult(request,getShaderIdDirect(request.key));
	}
}
Пример #30
0
void TextureSource::processQueue()
{
	/*
		Fetch textures
	*/
	if(!m_get_texture_queue.empty())
	{
		GetRequest<std::string, u32, u8, u8>
				request = m_get_texture_queue.pop();

		/*infostream<<"TextureSource::processQueue(): "
				<<"got texture request with "
				<<"name=\""<<request.key<<"\""
				<<std::endl;*/

		m_get_texture_queue.pushResult(request,getTextureIdDirect(request.key));
	}
}