Exemple #1
0
void TracerManager::output(const string &fileName)
{
    // -------------------------------------------------------------------------
    // output polygon stuffs
    polygonManager.output(fileName);
#ifdef TTS_REMAP
    // -------------------------------------------------------------------------
    NcFile file(fileName.c_str(), NcFile::Write);
    if (!file.is_valid()) {
        Message message;
        message << "Failed to open tracer output file \"";
        message << fileName << "\" for appending meshed density field!";
        REPORT_ERROR(message.str());
    }
    // -------------------------------------------------------------------------
    // output tracer densities on the polygons
    NcDim *numPolygonDim = file.get_dim("num_total_polygon");
    double q0[polygonManager.polygons.size()];
    for (int l = 0; l < tracerNames.size(); ++l) {
        char varName[30];
        sprintf(varName, "q%d", l);
        NcVar *qVar = file.add_var(varName, ncDouble, numPolygonDim);
        Polygon *polygon = polygonManager.polygons.front();
        for (int i = 0; i < polygonManager.polygons.size(); ++i) {
            q0[i] = polygon->tracers[l].getDensity();
            polygon = polygon->next;
        }
        qVar->put(q0, polygonManager.polygons.size());
    }
    // -------------------------------------------------------------------------
    // output tracer densities on the mesh
    const RLLMesh &mesh = tracerDensities[0].getMesh();
    int numLon = mesh.getNumLon()-2;
    int numLat = mesh.getNumLat();
    double lon[numLon], lat[numLat];
    for (int i = 0; i < numLon; ++i)
        lon[i] = mesh.lon(i+1)*Rad2Deg;
    for (int j = 0; j < numLat; ++j)
        lat[j] = mesh.lat(j)*Rad2Deg;
    NcDim *lonDim = file.add_dim("lon", numLon);
    NcDim *latDim = file.add_dim("lat", numLat);
    NcVar *lonVar = file.add_var("lon", ncDouble, lonDim);
    lonVar->add_att("long_name", "longitude");
    lonVar->add_att("units", "degrees_east");
    lonVar->put(lon, numLon);
    NcVar *latVar = file.add_var("lat", ncDouble, latDim);
    latVar->add_att("long_name", "latitude");
    latVar->add_att("units", "degrees_north");
    latVar->put(lat, numLat);
    NcVar *areaVar = file.add_var("area_mesh", ncDouble, latDim, lonDim);
    areaVar->add_att("long_name", "area of fixed mesh cell");
    areaVar->add_att("units", "m2");
    double area[numLat][numLon];
    for (int i = 0; i < numLon; ++i)
        for (int j = 0; j < numLat; ++j)
            area[j][i] = tracerDensities[0].getMesh(Field::Bound).area(i, j);
    areaVar->put(&area[0][0], numLat, numLon);
    double q[numLat][numLon];
    for (int l = 0; l < tracerNames.size(); ++l) {
        char varName[30];
        sprintf(varName, "q%d_mesh", l);
        NcVar *qVar = file.add_var(varName, ncDouble, latDim, lonDim);
        qVar->add_att("long_name", tracerNames[l].c_str());
        for (int i = 0; i < numLon; ++i)
            for (int j = 0; j < numLat; ++j)
                q[j][i] = tracerDensities[l].values(i+1, j, 0).getNew();
        qVar->put(&q[0][0], numLat, numLon);
    }
    // -------------------------------------------------------------------------
    file.close();
#endif
    NOTICE("TracerManager", fileName+" is generated.");
}
// This function implements the NcpFrameBuffer tests
void TestNcpFrameBuffer(void)
{
    unsigned i, j;
    uint8_t buffer[kTestBufferSize];
    NcpFrameBuffer ncpBuffer(buffer, kTestBufferSize);

    Message *message;
    CallbackContext context;
    CallbackContext oldContext;
    uint8_t readBuffer[16];
    uint16_t readLen, readOffset;

    for (i = 0; i < sizeof(buffer); i++)
    {
        buffer[i] = 0;
    }

    context.mEmptyCount = 0;
    context.mNonEmptyCount = 0;

    // Set the callbacks.
    ncpBuffer.SetCallbacks(BufferDidGetEmptyCallback, BufferDidGetNonEmptyCallback, &context);

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 1: Write a frame 1 ");

    WriteTestFrame1(ncpBuffer);
    DumpBuffer("\nBuffer after frame1", buffer, kTestBufferSize);
    printf("\nFrameLen is %u", ncpBuffer.OutFrameGetLength());

    VerifyAndRemoveFrame1(ncpBuffer);

    printf("\nIterations: ");

    // Repeat this multiple times.
    for (j = 0; j < kTestIterationAttemps; j++)
    {
        printf("*");
        WriteTestFrame1(ncpBuffer);
        VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non-empty");

        VerifyAndRemoveFrame1(ncpBuffer);
        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 2: Multiple frames write and read ");

    WriteTestFrame2(ncpBuffer);
    WriteTestFrame3(ncpBuffer);
    WriteTestFrame2(ncpBuffer);
    WriteTestFrame2(ncpBuffer);

    DumpBuffer("\nBuffer after multiple frames", buffer, kTestBufferSize);

    VerifyAndRemoveFrame2(ncpBuffer);
    VerifyAndRemoveFrame3(ncpBuffer);
    VerifyAndRemoveFrame2(ncpBuffer);
    VerifyAndRemoveFrame2(ncpBuffer);

    printf("\nIterations: ");

    // Repeat this multiple times.
    for (j = 0; j < kTestIterationAttemps; j++)
    {
        printf("*");

        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);
        WriteTestFrame2(ncpBuffer);

        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame3(ncpBuffer);

        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);

        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame3(ncpBuffer);

        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 3: Frame discard when buffer full and partial read restart");

    for (j = 0; j < kTestIterationAttemps; j++)
    {
        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);

        ncpBuffer.InFrameBegin();
        ncpBuffer.InFrameFeedData(sHelloText, sizeof(sHelloText));

        message = sMessagePool.New(Message::kTypeIp6, 0);
        VerifyOrQuit(message != NULL, "Null Message");
        SuccessOrQuit(message->SetLength(sizeof(sMysteryText)), "Could not set the length of message.");
        message->Write(0, sizeof(sMysteryText), sMysteryText);

        ncpBuffer.InFrameFeedMessage(*message);

        // Now cause a restart the current frame and test if it's discarded ok.
        WriteTestFrame2(ncpBuffer);

        if (j == 0)
        {
            DumpBuffer("\nAfter frame gets discarded", buffer, kTestBufferSize);
            printf("\nIterations: ");
        }
        else
        {
            printf("*");
        }

        VerifyAndRemoveFrame2(ncpBuffer);

        // Start reading few bytes from the frame
        ncpBuffer.OutFrameBegin();
        ncpBuffer.OutFrameReadByte();
        ncpBuffer.OutFrameReadByte();
        ncpBuffer.OutFrameReadByte();

        // Now reset the read pointer and read/verify the frame from start.
        VerifyAndRemoveFrame3(ncpBuffer);
        VerifyAndRemoveFrame2(ncpBuffer);

        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 4: Callbacks ");

    printf("\nIterations: ");

    // Repeat this multiple times.
    for (j = 0; j < kTestIterationAttemps; j++)
    {
        printf("*");
        oldContext = context;
        WriteTestFrame2(ncpBuffer);
        VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non-empty");
        VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly");
        VerifyOrQuit(oldContext.mNonEmptyCount + 1 == context.mNonEmptyCount, "NonEmpty callback was not invoked.");

        oldContext = context;
        WriteTestFrame3(ncpBuffer);
        VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly");
        VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly.");

        oldContext = context;
        ncpBuffer.OutFrameRemove();
        VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non empty.");
        VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly");
        VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly.");

        oldContext = context;
        ncpBuffer.OutFrameRemove();
        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
        VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked.");
        VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 5: Clear() and empty buffer method tests");

    WriteTestFrame1(ncpBuffer);

    oldContext = context;
    ncpBuffer.Clear();

    VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer.");
    VerifyOrQuit(ncpBuffer.OutFrameRemove() == kThreadError_NotFound,
                 "Remove() returned incorrect error status when buffer is empty.");
    VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty.");
    VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked.");
    VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly.");

    WriteTestFrame1(ncpBuffer);

    oldContext = context;
    VerifyAndRemoveFrame1(ncpBuffer);

    VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer.");
    VerifyOrQuit(ncpBuffer.OutFrameRemove() == kThreadError_NotFound,
                 "Remove() returned incorrect error status when buffer is empty.");
    VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty.");
    VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked.");
    VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly.");

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 6: OutFrameRead() in parts\n");

    ncpBuffer.InFrameBegin();
    ncpBuffer.InFrameFeedData(sMottoText, sizeof(sMottoText));
    ncpBuffer.InFrameEnd();

    ncpBuffer.OutFrameBegin();
    readOffset = 0;

    while ((readLen = ncpBuffer.OutFrameRead(sizeof(readBuffer), readBuffer)) != 0)
    {
        DumpBuffer("Read() returned", readBuffer, readLen);

        VerifyOrQuit(memcmp(readBuffer, sMottoText + readOffset, readLen) == 0,
                     "Read() does not match expected content.");

        readOffset += readLen;
    }

    VerifyOrQuit(readOffset == sizeof(sMottoText), "Read len does not match expected length.");
    printf("\n -- PASS\n");
}
void Client::ProcessReceivedMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    Header responseHeader;
    Header requestHeader;
    RequestMetadata requestMetadata;
    Message *message = NULL;
    ThreadError error;

    SuccessOrExit(error = responseHeader.FromMessage(aMessage, false));
    aMessage.MoveOffset(responseHeader.GetLength());

    message = FindRelatedRequest(responseHeader, aMessageInfo, requestHeader, requestMetadata);

    if (message == NULL)
    {
        ExitNow();
    }

    switch (responseHeader.GetType())
    {
    case kCoapTypeReset:
        if (responseHeader.IsEmpty())
        {
            FinalizeCoapTransaction(*message, requestMetadata, NULL, NULL, NULL, kThreadError_Abort);
        }

        // Silently ignore non-empty reset messages (RFC 7252, p. 4.2).
        break;

    case kCoapTypeAcknowledgment:
        if (responseHeader.IsEmpty())
        {
            // Empty acknowledgment.
            if (requestMetadata.mConfirmable)
            {
                requestMetadata.mAcknowledged = true;
                requestMetadata.UpdateIn(*message);
            }

            // Remove the message if response is not expected, otherwise await response.
            if (requestMetadata.mResponseHandler == NULL)
            {
                DequeueMessage(*message);
            }
        }
        else if (responseHeader.IsResponse() && responseHeader.IsTokenEqual(requestHeader))
        {
            // Piggybacked response.
            FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, &aMessageInfo, kThreadError_None);
        }

        // Silently ignore acknowledgments carrying requests (RFC 7252, p. 4.2)
        // or with no token match (RFC 7252, p. 5.3.2)
        break;

    case kCoapTypeConfirmable:
    case kCoapTypeNonConfirmable:
        if (responseHeader.IsConfirmable())
        {
            // Send empty ACK if it is a CON message.
            SendEmptyAck(aMessageInfo.GetPeerAddr(), aMessageInfo.GetPeerPort(), responseHeader.GetMessageId());
        }

        FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, &aMessageInfo, kThreadError_None);

        break;
    }

exit:

    if (error == kThreadError_None && message == NULL)
    {
        if (responseHeader.IsConfirmable() || responseHeader.IsNonConfirmable())
        {
            // Successfully parsed a header but no matching request was found - reject the message by sending reset.
            SendReset(aMessageInfo.GetPeerAddr(), aMessageInfo.GetPeerPort(), responseHeader.GetMessageId());
        }
    }
}
Exemple #4
0
void *SearchDialog::processEvent(Event *e)
{
    switch (e->type()){
    case EventClientsChanged:
    case EventClientChanged:
        fillClients();
        break;
    case EventCommandExec:{
            if (m_result != m_currentResult)
                return NULL;
            CommandDef *cmd = (CommandDef*)(e->param());
            if (cmd->menu_id == MenuSearchGroups){
                Group *grp = getContacts()->group(cmd->id - CmdContactGroup);
                if (grp){
                    Contact *contact = NULL;
                    if ((QWidget*)(cmd->param) == m_search->btnSearch){
                        if (m_current){
                            connect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
                            emit createContact(CONTACT_TEMP, contact);
                            disconnect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
                        }
                    }else{
                        contact = createContact(CONTACT_TEMP);
                    }
                    if (contact){
                        if ((contact->getFlags() & CONTACT_TEMP) == 0){
                            QString err = i18n("%1 already in contact list") .arg(contact->getName());
                            if ((QWidget*)(cmd->param) == m_search->btnAdd){
                                BalloonMsg::message(err, m_search->btnAdd);
                            }else if ((QWidget*)(cmd->param) == m_search->btnSearch){
                                BalloonMsg::message(err, m_search->btnSearch);
                            }else{
                                BalloonMsg::message(err, m_result);
                            }
                            return e->param();
                        }
                        contact->setFlags(contact->getFlags() & ~CONTACT_TEMP);
                        contact->setGroup(grp->id());
                        Event e(EventContactChanged, contact);
                        e.process();
                    }
                }
                return e->param();
            }
            if (cmd->id == CmdSearchInfo){
                Contact *contact = createContact(CONTACT_TEMP);
                if (contact == NULL)
                    return e->param();
                Command cmd;
                cmd->id		 = CmdInfo;
                cmd->menu_id = MenuContact;
                cmd->param   = (void*)(contact->id());
                CorePlugin::m_plugin->showInfo(cmd);
                return e->param();
            }
            if (cmd->id == CmdSearchMsg){
                Contact *contact = createContact(CONTACT_TEMP);
                if (contact == NULL)
                    return e->param();
                Message *m = new Message(MessageGeneric);
                m->setContact(contact->id());
                Event e(EventOpenMessage, &m);
                e.process();
                delete m;
            }
            break;
        }
void DSPEngine::configureCorrections(bool dcOffsetCorrection, bool iqImbalanceCorrection)
{
	Message* cmd = DSPConfigureCorrection::create(dcOffsetCorrection, iqImbalanceCorrection);
	cmd->submit(&m_messageQueue);
}
Exemple #6
0
    /**
     * This is called by db/ops/query.cpp.  This is the entry point for answering a query.
     */
    string newRunQuery(Message& m, QueryMessage& q, CurOp& curop, Message &result) {
        // This is a read lock.
        Client::ReadContext ctx(q.ns, dbpath);

        // Parse, canonicalize, plan, transcribe, and get a runner.
        Runner* rawRunner;
        Status status = getRunner(q, &rawRunner);
        if (!status.isOK()) {
            uasserted(17007, "Couldn't process query " + q.query.toString()
                         + " why: " + status.reason());
        }
        verify(NULL != rawRunner);
        auto_ptr<Runner> runner(rawRunner);

        // We freak out later if this changes before we're done with the query.
        const ChunkVersion shardingVersionAtStart = shardingState.getVersion(q.ns);

        // We use this a lot below.
        const ParsedQuery& pq = runner->getQuery().getParsed();

        // TODO: Document why we do this.
        replVerifyReadsOk(&pq);

        // If this exists, the collection is sharded.
        // If it doesn't exist, we can assume we're not sharded.
        // If we're sharded, we might encounter data that is not consistent with our sharding state.
        // We must ignore this data.
        CollectionMetadataPtr collMetadata;
        if (!shardingState.needCollectionMetadata(pq.ns())) {
            collMetadata = CollectionMetadataPtr();
        }
        else {
            collMetadata = shardingState.getCollectionMetadata(pq.ns());
        }

        // Run the query.
        BufBuilder bb(32768);
        bb.skip(sizeof(QueryResult));

        // How many results have we obtained from the runner?
        int numResults = 0;

        // If we're replaying the oplog, we save the last time that we read.
        OpTime slaveReadTill;

        // Do we save the Runner in a ClientCursor for getMore calls later?
        bool saveClientCursor = false;

        BSONObj obj;
        // TODO: Differentiate EOF from error.
        while (runner->getNext(&obj)) {
            // If we're sharded make sure that we don't return any data that hasn't been migrated
            // off of our shared yet.
            if (collMetadata) {
                // This information can change if we yield and as such we must make sure to re-fetch
                // it if we yield.
                KeyPattern kp(collMetadata->getKeyPattern());
                // This performs excessive BSONObj creation but that's OK for now.
                if (!collMetadata->keyBelongsToMe(kp.extractSingleKey(obj))) { continue; }
            }

            // Add result to output buffer.
            bb.appendBuf((void*)obj.objdata(), obj.objsize());

            // Count the result.
            ++numResults;

            // Possibly note slave's position in the oplog.
            if (pq.hasOption(QueryOption_OplogReplay)) {
                BSONElement e = obj["ts"];
                if (Date == e.type() || Timestamp == e.type()) {
                    slaveReadTill = e._opTime();
                }
            }

            // TODO: only one type of 2d search doesn't support this.  We need a way to pull it out
            // of CanonicalQuery. :(
            const bool supportsGetMore = true;
            const bool isExplain = pq.isExplain();
            if (isExplain && pq.enoughForExplain(numResults)) {
                break;
            }
            else if (!supportsGetMore && (pq.enough(numResults)
                                          || bb.len() >= MaxBytesToReturnToClientAtOnce)) {
                break;
            }
            else if (pq.enoughForFirstBatch(numResults, bb.len())) {
                // If only one result requested assume it's a findOne() and don't save the cursor.
                if (pq.wantMore() && 1 != pq.getNumToReturn()) {
                    saveClientCursor = true;
                }
                break;
            }
        }

        // TODO: Stage creation can set tailable depending on what's in the parsed query.  We have
        // the full parsed query available during planning...set it there.
        //
        // TODO: If we're tailable we want to save the client cursor.  Make sure we do this later.
        //if (pq.hasOption(QueryOption_CursorTailable) && pq.getNumToReturn() != 1) { ... }

        // TODO(greg): This will go away soon.
        if (!shardingState.getVersion(pq.ns()).isWriteCompatibleWith(shardingVersionAtStart)) {
            // if the version changed during the query we might be missing some data and its safe to
            // send this as mongos can resend at this point
            throw SendStaleConfigException(pq.ns(), "version changed during initial query",
                                           shardingVersionAtStart,
                                           shardingState.getVersion(pq.ns()));
        }

        long long ccId = 0;
        if (saveClientCursor) {
            // Allocate a new ClientCursor.
            ClientCursorHolder ccHolder;
            ccHolder.reset(new ClientCursor(runner.get()));
            ccId = ccHolder->cursorid();

            // We won't use the runner until it's getMore'd.
            runner->saveState();

            // ClientCursor takes ownership of runner.  Release to make sure it's not deleted.
            runner.release();

            if (pq.hasOption(QueryOption_OplogReplay) && !slaveReadTill.isNull()) {
                ccHolder->slaveReadTill(slaveReadTill);
            }

            if (pq.hasOption(QueryOption_Exhaust)) {
                curop.debug().exhaust = true;
            }

            // Set attributes for getMore.
            ccHolder->setCollMetadata(collMetadata);
            ccHolder->setPos(numResults);

            // If the query had a time limit, remaining time is "rolled over" to the cursor (for
            // use by future getmore ops).
            ccHolder->setLeftoverMaxTimeMicros(curop.getRemainingMaxTimeMicros());

            // Give up our reference to the CC.
            ccHolder.release();
        }

        // Add the results from the query into the output buffer.
        result.appendData(bb.buf(), bb.len());
        bb.decouple();

        // Fill out the output buffer's header.
        QueryResult* qr = static_cast<QueryResult*>(result.header());
        qr->cursorId = ccId;
        curop.debug().cursorid = (0 == ccId ? -1 : ccId);
        qr->setResultFlagsToOk();
        qr->setOperation(opReply);
        qr->startingFrom = 0;
        qr->nReturned = numResults;
        // TODO: nscanned is bogus.
        // curop.debug().nscanned = ( cursor ? cursor->nscanned() : 0LL );
        curop.debug().ntoskip = pq.getSkip();
        curop.debug().nreturned = numResults;

        // curop.debug().exhaust is set above.
        return curop.debug().exhaust ? pq.ns() : "";
    }
Exemple #7
0
void BusHandler::receiveCompleted()
{
	unsigned char srcAddress = m_command[0], dstAddress = m_command[1];
	if (srcAddress == dstAddress) {
		logError(lf_bus, "invalid self-addressed message from %2.2x", srcAddress);
		return;
	}
	addSeenAddress(srcAddress);
	addSeenAddress(dstAddress);

	bool master = isMaster(dstAddress);
	if (dstAddress == BROADCAST) {
		logInfo(lf_update, "update BC cmd: %s", m_command.getDataStr().c_str());
		if (m_command.size()>=5+9 && m_command[2]==0x07 && m_command[3]==0x04) {
			unsigned char slaveAddress = (unsigned char)((srcAddress+5)&0xff);
			addSeenAddress(slaveAddress);
			Message* message = m_messages->getScanMessage(slaveAddress);
			if (message && (message->getLastUpdateTime()==0 || message->getLastSlaveData().size()<10)) {
				// e.g. 10fe07040a b5564149303001248901
				m_seenAddresses[slaveAddress] |= SCAN_INIT;
				SymbolString idData;
				istringstream input;
				result_t result = message->prepareMaster(m_ownMasterAddress, idData, input);
				if (result==RESULT_OK) {
					idData.clear();
					idData.push_back(9);
					for (size_t i = 5; i <= 5+9; i++) {
						idData.push_back(m_command[i]);
					}
					result = message->storeLastData(pt_slaveData, idData, 0);
				}
				if (result==RESULT_OK) {
					m_seenAddresses[slaveAddress] |= SCAN_DONE;
				}
				logNotice(lf_update, "store BC ident: %s", getResultCode(result));
			}
		}
	} else if (master) {
		logInfo(lf_update, "update MM cmd: %s", m_command.getDataStr().c_str());
	} else {
		logInfo(lf_update, "update MS cmd: %s / %s", m_command.getDataStr().c_str(), m_response.getDataStr().c_str());
	}
	Message* message = m_messages->find(m_command);
	if (m_grabMessages) {
		unsigned long long key;
		if (message) {
			key = message->getKey();
		} else {
			key = Message::createKey(m_command, 4); // up to 4 DD bytes
		}
		m_grabbedMessages[key].setLastData(m_command, m_response);
	}
	if (message == NULL) {
		if (dstAddress == BROADCAST) {
			logNotice(lf_update, "unknown BC cmd: %s", m_command.getDataStr().c_str());
		} else if (master) {
			logNotice(lf_update, "unknown MM cmd: %s", m_command.getDataStr().c_str());
		} else {
			logNotice(lf_update, "unknown MS cmd: %s / %s", m_command.getDataStr().c_str(), m_response.getDataStr().c_str());
		}
	} else {
		m_messages->invalidateCache(message);
		string circuit = message->getCircuit();
		string name = message->getName();
		result_t result = message->storeLastData(m_command, m_response);
		ostringstream output;
		if (result==RESULT_OK) {
			result = message->decodeLastData(output);
		}
		if (result < RESULT_OK) {
			logError(lf_update, "unable to parse %s %s from %s / %s: %s", circuit.c_str(), name.c_str(), m_command.getDataStr().c_str(), m_response.getDataStr().c_str(), getResultCode(result));
		} else {
			string data = output.str();
			if (m_answer && dstAddress == (master ? m_ownMasterAddress : m_ownSlaveAddress)) {
				logNotice(lf_update, "self-update %s %s QQ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, data.c_str()); // TODO store in database of internal variables
			} else if (message->getDstAddress() == SYN) { // any destination
				if (message->getSrcAddress() == SYN) { // any destination and any source
					logNotice(lf_update, "update %s %s QQ=%2.2x ZZ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, dstAddress, data.c_str());
				} else {
					logNotice(lf_update, "update %s %s ZZ=%2.2x: %s", circuit.c_str(), name.c_str(), dstAddress, data.c_str());
				}
			} else if (message->getSrcAddress() == SYN) { // any source
				logNotice(lf_update, "update %s %s QQ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, data.c_str());
			} else {
				logNotice(lf_update, "update %s %s: %s", circuit.c_str(), name.c_str(), data.c_str());
			}
		}
	}
}
void MessageTest::send()
{
  QCOMPARE(m_conn.messageCount(), 0);

  // Invalid message, no connection set
  Message invalidMessage;
  QCOMPARE(invalidMessage.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Invalid message, no connection set
  invalidMessage.setConnection(&m_conn);
  QCOMPARE(invalidMessage.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Valid message, no connection set
  Message request(Message::Request);
  request.setMethod("testMethod");
  QCOMPARE(request.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Test id generation for requests
  request.setConnection(&m_conn);
  QVERIFY(request.id().isNull());
  QCOMPARE(request.send(), true);
  QVERIFY(!request.id().isNull());
  QCOMPARE(m_conn.messageCount(), 1);

  // Id should match the message received by the connection:
  Message connMessage = m_conn.popMessage();
  MoleQueue::MessageIdType requestId = request.id();
  QCOMPARE(requestId, connMessage.id());

  // Resending the request should assign a different id.
  QCOMPARE(request.send(), true);
  QVERIFY(!request.id().isNull());
  QCOMPARE(m_conn.messageCount(), 1);

  // The new id should not match the old one:
  connMessage = m_conn.popMessage();
  QVERIFY(requestId != connMessage.id());

  // Sending any other type of message should not modify the ids.
  MoleQueue::MessageIdType testId(QLatin1String("testId"));

  // Notifications
  // (no id testing -- ids are not used.)
  Message notification(Message::Notification, &m_conn);
  notification.setMethod("testMethod");
  QCOMPARE(notification.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  m_conn.popMessage();

  // Response
  Message response(Message::Response, &m_conn);
  response.setId(testId);
  response.setMethod("testMethod");
  QCOMPARE(response.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  QCOMPARE(m_conn.popMessage().id(), testId);

  // Error
  Message error(Message::Error, &m_conn);
  error.setId(testId);
  error.setErrorCode(2);
  error.setErrorMessage("Test error");
  QCOMPARE(error.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  QCOMPARE(m_conn.popMessage().id(), testId);
}
void MessageTest::sanityCheck()
{
  // type
  Message invalid;
  QCOMPARE(invalid.type(), Message::Invalid);
  Message request(Message::Request);
  QCOMPARE(request.type(), Message::Request);
  Message notification(Message::Notification);
  QCOMPARE(notification.type(), Message::Notification);
  Message response(Message::Response);
  QCOMPARE(response.type(), Message::Response);
  Message error(Message::Error);
  QCOMPARE(error.type(), Message::Error);

  // method
  request.setMethod("Test");
  QCOMPARE(request.method(), QString("Test"));

  // params
  QJsonObject paramsObject;
  paramsObject.insert("test", QLatin1String("value"));
  request.setParams(paramsObject);
  QCOMPARE(request.params().toObject(), paramsObject);

  QJsonArray paramsArray;
  paramsArray.append(QString("Test"));
  request.setParams(paramsArray);
  QCOMPARE(request.params().toArray(), paramsArray);

  // result
  response.setResult(true);
  QCOMPARE(response.result().toBool(false), true);

  // errorCode
  int testInt = 867-5309;
  error.setErrorCode(testInt);
  QCOMPARE(error.errorCode(), testInt);

  // errorMessage
  QString testMessage = "Test Error Message";
  error.setErrorMessage(testMessage);
  QCOMPARE(error.errorMessage(), testMessage);

  // errorData
  error.setErrorData(false);
  QCOMPARE(error.errorData().toBool(true), false);

  // id
  MoleQueue::MessageIdType id(QString("IDIDIDID"));
  error.setId(id);
  QCOMPARE(error.id(), id);

  // connection
  error.setConnection(&m_conn);
  QCOMPARE(error.connection(), &m_conn);

  // endpoint
  MoleQueue::EndpointIdType endpoint("I'm an endpoint!!");
  error.setEndpoint(endpoint);
  QCOMPARE(error.endpoint(), endpoint);
}
void
SelectionTable::Receive
	(
	JBroadcaster* 	sender, 
	const Message& 	message
	)
{
	// Here we check to see what messages we have received.

	// We first check if the sender is our data array
	if (sender == itsData)
		{
		// Our data array sent us a message

		// Was data inserted?
		if (message.Is(JOrderedSetT::kElementsInserted))
			{
			// cast the message to an ElementsInserted object
			const JOrderedSetT::ElementsInserted* info = 
				dynamic_cast<const JOrderedSetT::ElementsInserted*>(&message);
			assert(info != NULL);

			// For each element inserted, we insert a row
			InsertRows(info->GetFirstIndex(), info->GetCount(), kDefRowHeight);
			}

		// Was data removed?
		else if (message.Is(JOrderedSetT::kElementsRemoved))
			{
			// cast the message to an ElementsRemoved object
			const JOrderedSetT::ElementsRemoved* info = 
				dynamic_cast<const JOrderedSetT::ElementsRemoved*>(&message);
			assert(info != NULL);

			// Remove corresponding table rows.
			for (JSize i = info->GetLastIndex(); i >= info->GetFirstIndex() ; i--)
				{
				RemoveNextRows(info->GetFirstIndex(), info->GetCount());
				}
			}

		// Was an element changed?
		else if (message.Is(JOrderedSetT::kElementChanged))
			{
			// cast the message to an ElementsRemoved object
			const JOrderedSetT::ElementChanged* info = 
				dynamic_cast<const JOrderedSetT::ElementChanged*>(&message);
			assert(info != NULL);

			// The element changed, so redraw it.
			// (This would not be necessary if we were using a
			//  class derived from JTableData.)
			TableRefreshRow(info->GetFirstIndex());
			}
		}

	// Did the Table menu send a message?
	else if (sender == itsTableMenu)
		{
		// Does the menu need an update?
		if (message.Is(JXMenu::kNeedsUpdate))
			{
			UpdateTableMenu();
			}

		// Has a menu item been selected?
		else if (message.Is(JXMenu::kItemSelected))
			{
			// cast the message to an ItemSelecte object.
			// This will tell us which item was selected.
			const JXMenu::ItemSelected* info = 
				dynamic_cast<const JXMenu::ItemSelected*>(&message);
			assert(info != NULL);

			// Pass the selected menu item to our menu handler function.
			HandleTableMenu(info->GetIndex());
			}
		}

	// pass the message to our base class
	else
		{
		JXTable::Receive(sender, message);
		}
}
void MessageTest::toJson()
{
  // Misc objects used in testing:
  QJsonObject testObject;
  testObject.insert("test", QLatin1String("value"));

  QJsonArray testArray;
  testArray.append(QString("Test"));

  QJsonArray testCompositeArray;
  testCompositeArray.append(MoleQueue::idTypeToJson(MoleQueue::InvalidId));
  testCompositeArray.append(testObject);
  testCompositeArray.append(testArray);
  testCompositeArray.append(true);
  testCompositeArray.append(5);
  testCompositeArray.append(5.36893473232); // This will be truncated to %.5f!
  testCompositeArray.append(QString("Abrakadabra"));

  // Test that the idtypeutils is working as expected.
  QVERIFY(testCompositeArray.first().isNull());
  QCOMPARE(MoleQueue::toIdType(testCompositeArray.first()),
           MoleQueue::InvalidId);

  // Invalid message
  Message invalid;
  QCOMPARE(QString(invalid.toJson()),
           QString(ReferenceString("message-ref/invalidJson.json")));

  // Request -- no params
  Message request(Message::Request);
  request.setMethod("testMethod");
  request.setId(MoleQueue::MessageIdType(1));
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-noParams.json")));

  // Request -- object params
  request.setParams(testObject);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-objectParams.json")));

  // Request -- array params
  request.setParams(testArray);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-arrayParams.json")));

  // Notification -- no params
  Message notification(Message::Notification);
  notification.setMethod("poke");
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-noParams.json")));

  // Notification -- object params
  notification.setParams(testObject);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-objectParams.json")));

  // Notification -- array params
  notification.setParams(testArray);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-arrayParams.json")));

  // Response
  Message response(Message::Response);
  response.setId(MoleQueue::MessageIdType(42));
  response.setMethod("Won't be in JSON string for response.");
  response.setResult(testCompositeArray);
  QCOMPARE(QString(response.toJson()),
           QString(ReferenceString("message-ref/responseJson.json")));

  // Error -- no data
  Message error(Message::Error);
  error.setId(MoleQueue::MessageIdType(13));
  error.setMethod("Won't be in JSON string for error.");
  error.setErrorCode(666);
  error.setErrorMessage("Server is possessed.");
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-noData.json")));

  // Error -- primitive data
  error.setErrorData(55);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-primData.json")));

  // Error -- object data
  error.setErrorData(testObject);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-objectData.json")));

  // Error -- array data
  error.setErrorData(testArray);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-arrayData.json")));
}
Exemple #12
0
void Node::answer_to_changeroot(Message& msg)
{
    int sender_index = msg.get_sender_ID();
    fp.write("Recv: Changeroot from host" + to<>(sender_index) + " on (" + to<>(sender_index) + "-" + to<>(index));
    changeroot();
}
Exemple #13
0
quint16 ClientPrivate::sendPublish(Message &msg)
{
    quint8 header = PUBLISH;
    header = SETRETAIN(header, msg.retain() ? 1 : 0);
    header = SETQOS(header, msg.qos());
    header = SETDUP(header, msg.dup() ? 1 : 0);
    Frame frame(header);
    frame.writeString(msg.topic());
    if(msg.qos() > MQTT_QOS0) {
        if(msg.id() == 0) {
            msg.setId(gmid++);
        }
        frame.writeInt(msg.id());
    }
    if(!msg.payload().isEmpty()) {
        frame.writeRawData(msg.payload());
    }
    network->sendFrame(frame);
    return msg.id();
}
Exemple #14
0
void TracerManager::registerTracer(const string &fileName,
                                   const MeshManager &meshManager)
{
    // -------------------------------------------------------------------------
    // parse and read file
    NcError ncError(NcError::silent_nonfatal);

    NcFile file(fileName.c_str(), NcFile::ReadOnly);
    if (!file.is_valid()) {
        Message message;
        message << "Failed to open tracer file \"" << fileName << "\"!";
        REPORT_ERROR(message.str());
    }

    if (file.get_att("name") == NULL) {
        Message message;
        message << "There is no \"name\" attribute in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    tracerNames.push_back(file.get_att("name")->as_string(0));

    if (file.get_att("name") == NULL) {
        Message message;
        message << "There is no \"name\" attribute in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    tracerNames.push_back(file.get_att("name")->as_string(0));

    int numPolygon = static_cast<int>(file.get_dim("num_total_polygon")->size());
    if (numPolygon != polygonManager.polygons.size()) {
        Message message;
        message << "Polygon numbers (" << numPolygon << " != ";
        message << polygonManager.polygons.size();
        message << ") are not consistent in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    double mass[numPolygon];
    if (file.get_var("mass") == NULL) {
        Message message;
        message << "There is no \"mass\" variable in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    file.get_var("mass")->get(mass);
    // -------------------------------------------------------------------------
    // initialize tracer density on the mesh
    tracerDensities.push_back(Field());
    if (meshManager.hasLayers())
        tracerDensities.back().init(meshManager.getMesh(PointCounter::Center),
                                    meshManager.getMesh(PointCounter::Bound),
                                    meshManager.getLayers(Layers::Full));
    else
        tracerDensities.back().init(meshManager.getMesh(PointCounter::Center),
                                    meshManager.getMesh(PointCounter::Bound));
    // -------------------------------------------------------------------------
    // set up tracer variables in polygons
    int tracerId = static_cast<int>(tracerNames.size()-1);
    Polygon *polygon = polygonManager.polygons.front();
    for (int i = 0; i < polygonManager.polygons.size(); ++i) {
        polygon->tracers.push_back(Tracer());
        polygon->tracers[tracerId].setMass(mass[i]);
        polygon = polygon->next;
    }
}
Exemple #15
0
int
ActorSubdomain::run(void)
{
    static Vector theVect(4);
	static Vector theVect1(1);
    bool exitYet = false;
    int res = 0;

    while (exitYet == false) {
      int action;
      res = this->recvID(msgData);
      if (res != 0) {
	opserr << "ActorSubdomain::run - error receiving msgData\n";
	exitYet = true;
        action = ShadowActorSubdomain_DIE;
      } else {
	action = msgData(0);
      }

      bool change;
      int theType, theOtherType, tag, dbTag, loadPatternTag;
      int startTag, endTag, axisDirn, numSP, i, numMode, dof;
      Element *theEle;
      Node *theNod;
      SP_Constraint *theSP;
      MP_Constraint *theMP;
      LoadPattern *theLoadPattern;
      NodalLoad *theNodalLoad;
      ElementalLoad *theElementalLoad;
      DomainDecompositionAnalysis *theDDAnalysis;
      const Matrix *theMatrix;
      const Vector *theVector;
      Matrix *theM;
      Vector *theV;
      ID     *theI, *theNodeTags, *theEleTags;
      PartitionedModelBuilder *theBuilder;
      IncrementalIntegrator *theIntegrator;
      EquiSolnAlgo *theAlgorithm;
      LinearSOE *theSOE;
      EigenSOE *theEigenSOE;
      ConvergenceTest *theTest;
      Recorder *theRecorder;
      bool res, generalized, findSmallest;
      double doubleRes;
      int intRes;
      NodeResponseType nodeResponseType;
      Parameter *theParameter;
      int argc;
      char **argv;
      char *allResponseArgs;
      char *currentLoc;
      int argLength, msgLength;
      Message theMessage;

      const ID *theID;
      
      //     opserr << "ActorSubdomain ACTION: " << action << endln;

      switch (action) {
	  case ShadowActorSubdomain_setTag:
	    tag = msgData(1); // subdomain tag
	    this->setTag(tag);
	    this->Actor::setCommitTag(tag);
	    break;

	  case ShadowActorSubdomain_analysisStep:
	    this->recvVector(theVect);
	    this->analysisStep(theVect(0));
	    break;

	  case ShadowActorSubdomain_eigenAnalysis:
	    numMode = msgData(1);
	    if (msgData(2) == 0)
	      generalized = true;
	    else
	      generalized = false;
	    if (msgData(3) == 0)
	      findSmallest = true;
	    else
	      findSmallest = false;
		
	    this->eigenAnalysis(numMode, generalized, findSmallest);
	    break;
	    /*
	  case ShadowActorSubdomain_buildSubdomain:
	    theType = msgData(1);
	    tag = msgData(3); // subdomain tag
	    this->setTag(tag);
	    tag = msgData(2); // numSubdomains
	    theBuilder = theBroker->getPtrNewPartitionedModelBuilder(*this, 
								     theType);
	    this->recvObject(*theBuilder);
	    this->buildSubdomain(tag, *theBuilder);

	    break;
	    */
	case ShadowActorSubdomain_getRemoteData:
	    theID = &(this->getExternalNodes());
	    msgData(0) = theID->Size();
	    msgData(1) = this->getNumDOF();

	    this->sendID(msgData);
	    if (theID->Size() != 0)
	      this->sendID(*theID);
	    break;

	  case ShadowActorSubdomain_getCost:
       	    theVect(0) = this->getCost(); // have to use [] for Sun's CC!
	    this->sendVector(theVect);
	    break;	    

 	  case ShadowActorSubdomain_addElement:
	    theType = msgData(1);
	    dbTag = msgData(2);

	    theEle = theBroker->getNewElement(theType);

	    if (theEle != 0) {
		theEle->setDbTag(dbTag);		
		this->recvObject(*theEle);
		bool result = this->addElement(theEle);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    /*
	    this->recvID(msgData);	    
	    opserr << "ActorSubdomain::addElement() : " << msgData;
	    
	    msgData(0) = 1;
	    msgData(1) = 2;
	    msgData(2) = 3;
	    msgData(3) = 4;
	    this->sendID(msgData);	    
	    */

	    break;

	    
	  case ShadowActorSubdomain_hasNode:
	    theType = msgData(1);
	    res = this->hasNode(theType);
	    if (res == true)
	      msgData(0) = 0;
	    else
	      msgData(0) = -1;
	    this->sendID(msgData);

	    break;

	  case ShadowActorSubdomain_hasElement:
	    theType = msgData(1);
	    res = this->hasElement(theType);
	    if (res == true)
	      msgData(0) = 0;
	    else
	      msgData(0) = -1;
	    this->sendID(msgData);
	   
             break;


	  case ShadowActorSubdomain_addNode:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    theNod = theBroker->getNewNode(theType);

	    if (theNod != 0) {
		theNod->setDbTag(dbTag);		
		this->recvObject(*theNod); 
		bool result = this->addNode(theNod);
		if (result == true)
		  msgData(0) = 0;
		else
		  msgData(0) = -1;
	    } else
		msgData(0) = -1;
	    //	    opserr << "ActorSubdomain::add node: " << *theNod;
	    break;


	  case ShadowActorSubdomain_addExternalNode:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    theNod = theBroker->getNewNode(theType);

	    if (theNod != 0) {
		theNod->setDbTag(dbTag);
		this->recvObject(*theNod);
		bool result = this->Subdomain::addExternalNode(theNod);
		delete theNod;
		/*
		Node *dummy = new Node(*theNod);
		delete theNod;
		opserr << *dummy;
		opserr << dummy->getMass();
		*/

		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    

	    
	  case ShadowActorSubdomain_addSP_Constraint:
	    theType = msgData(1);
	    dbTag = msgData(2);

	    theSP = theBroker->getNewSP(theType);
	    
	    if (theSP != 0) {
		theSP->setDbTag(dbTag);
		this->recvObject(*theSP);
		bool result = this->addSP_Constraint(theSP);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    


	  case ShadowActorSubdomain_addSP_ConstraintAXIS:

	    axisDirn = msgData(1);
	    theI = new ID(msgData(2));
	    theV = new Vector(2);
	    SP_Constraint_SetNextTag(msgData(3));

	    endTag = 0;
		
	    this->recvID(*theI);
	    this->recvVector(*theV);

	    msgData(0) = 0;				 
	    numSP = this->addSP_Constraint(axisDirn, (*theV)(0), *theI, (*theV)(1));
	    endTag = SP_Constraint_GetNextTag();

	    msgData(1) = numSP;
	    msgData(2) = endTag;

	    this->domainChange();
	    this->sendID(msgData);
		
	    delete theV;
	    delete theI;
		
	    /* DONT BOTHER SENDING
	    if (numSP > 0) {
	      theI = new ID(numSP);
	      for (i = 0; i<numSP; i++) {
		theSP = this->getSP_Constraint(i+startTag);
		(*theI)(i) = theSP->getClassTag();
	      }
	      this->sendID(*theI);	
		  opserr << "Actor: sent: " << *theI;
	      for (i = 0; i<numSP; i++) {
		theSP = this->getSP_Constraint(i+startTag);
		if (theSP != 0)
		this->sendObject(*theSP);	
		else
			opserr << "ActorSubdomain::addSP_AXIS :: PROBLEMS\n";
	      }
	      delete theI;
	    }
opserr << "ActorSubdomain::addSP_AXIS :: DONE\n";
        */

	    break;	    
	    
	  case ShadowActorSubdomain_addMP_Constraint:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    theMP = theBroker->getNewMP(theType);

	    if (theMP != 0) {
		theMP->setDbTag(dbTag);
		this->recvObject(*theMP);
		bool result = this->addMP_Constraint(theMP);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;
		
	    break;	    
	    
	    
	  case ShadowActorSubdomain_addLoadPattern:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    
	    theLoadPattern = theBroker->getNewLoadPattern(theType);

	    if (theLoadPattern != 0) {
		theLoadPattern->setDbTag(dbTag);
		this->recvObject(*theLoadPattern);
		bool result = this->addLoadPattern(theLoadPattern);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    	    

	  case ShadowActorSubdomain_addNodalLoadToPattern:
 	    theType = msgData(1);
	    dbTag = msgData(2);
	    loadPatternTag = msgData(3);
	    
	    theNodalLoad = theBroker->getNewNodalLoad(theType);

	    if (theNodalLoad != 0) {
		theNodalLoad->setDbTag(dbTag);
		this->recvObject(*theNodalLoad);
		bool result = this->addNodalLoad(theNodalLoad, loadPatternTag);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    
	    
	    
	  case ShadowActorSubdomain_addElementalLoadToPattern:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    loadPatternTag = msgData(3);
	    
	    theElementalLoad = theBroker->getNewElementalLoad(theType);

	    if (theElementalLoad != 0) {
		theElementalLoad->setDbTag(dbTag);
		this->recvObject(*theElementalLoad);
		bool result = this->addElementalLoad(theElementalLoad, 
						     loadPatternTag);
		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    	    
	    
	  case ShadowActorSubdomain_addSP_ConstraintToPattern:
	    theType = msgData(1);
	    dbTag = msgData(2);
	    loadPatternTag = msgData(3);
	    
	    theSP = theBroker->getNewSP(theType);

	    if (theSP != 0) {
		theSP->setDbTag(dbTag);
		this->recvObject(*theSP);
		bool result = this->addSP_Constraint(theSP, loadPatternTag);

		if (result == true)
		    msgData(0) = 0;
		else
		    msgData(0) = -1;
	    } else
		msgData(0) = -1;

	    break;	    	    	    

	  case ShadowActorSubdomain_removeElement:
	    tag = msgData(1);

	    theEle = this->removeElement(tag);

	    if (theEle != 0) 
		msgData(0) = theEle->getClassTag();
	    else
		msgData(0) = -1;

	    this->sendID(msgData);
	    if (theEle != 0) {
		this->sendObject(*theEle);
		delete theEle;
	    }

	    msgData(0) = 0;

	    break;	    	    	    


	  case ShadowActorSubdomain_removeNode:
	    tag = msgData(1);

	    theNod = this->removeNode(tag);

	    if (theNod != 0) 
		msgData(0) = theNod->getClassTag();
	    else
		msgData(0) = -1;

	    this->sendID(msgData);
	    if (theNod != 0) {
		this->sendObject(*theNod);
		delete theNod;
	    }

	    msgData(0) = 0;

	    break;

	  case ShadowActorSubdomain_removeSP_Constraint:
	    tag = msgData(1);

	    theSP = this->removeSP_Constraint(tag);

	    break;	    

	  case ShadowActorSubdomain_removeSP_ConstraintNoTag:
	    tag = msgData(1);
	    dof = msgData(2);
	    loadPatternTag = msgData(3);
	    msgData(0) = this->removeSP_Constraint(tag, dof, loadPatternTag);
	    this->sendID(msgData);

	    break;	    
	    
	  case ShadowActorSubdomain_removeMP_Constraint:
	    tag = msgData(1);

	    theMP = this->removeMP_Constraint(tag);

	    break;	    	    

	  case ShadowActorSubdomain_removeLoadPattern:
	    tag = msgData(1);

	    theLoadPattern = this->removeLoadPattern(tag);

	    break;	    	    
	    
	  case ShadowActorSubdomain_removeNodalLoadFromPattern:
	    tag = msgData(1);
	    theType = msgData(2);

	    theNodalLoad = this->removeNodalLoad(tag, theType);

	    break;	    	    	    

	  case ShadowActorSubdomain_removeElementalLoadFromPattern:
	    tag = msgData(1);
	    theType = msgData(2);

	    theElementalLoad = this->removeElementalLoad(tag, theType);

	    break;	    	    	    

	  case ShadowActorSubdomain_removeSP_ConstraintFromPattern:
	    tag = msgData(1);
	    theType = msgData(2);

	    theSP = this->removeSP_Constraint(tag, theType);

	    break;	    	    	    
	    
	    
	    
	  case ShadowActorSubdomain_getElement:
	    tag = msgData(1);

	    theEle = this->getElement(tag);

	    if (theEle != 0) 
		msgData(0) = theEle->getClassTag();
	    else
		msgData(0) = -1;

	    this->sendID(msgData);
	    if (theEle != 0) {
		this->sendObject(*theEle);
	    }

	    msgData(0) = 0;

	    break;	    	    	    	    


	  case ShadowActorSubdomain_getNode:
	    tag = msgData(1);

	    theNod = this->getNode(tag);

	    if (theNod != 0) 
		msgData(0) = theNod->getClassTag();
	    else
		msgData(0) = -1;

	    this->sendID(msgData);

	    if (theNod != 0) {
		this->sendObject(*theNod);
	    }

	    msgData(0) = 0;

	    break;	    	    	    	    


	  case ShadowActorSubdomain_Print:
	    this->Print(opserr, msgData(3));
	    this->sendID(msgData);

	    break;	    	    	    	    

	  case ShadowActorSubdomain_PrintNodeAndEle:
	    
	    theNodeTags = 0;
	    theEleTags = 0;

	    if (msgData(1) != 0) {
	      theNodeTags = new ID(msgData(1));
	      this->recvID(*theNodeTags);
	    }
	    if (msgData(2) != 0) {
	      theEleTags = new ID(msgData(2));
	      this->recvID(*theEleTags);
	    }
	      
	    this->Print(opserr, theNodeTags, theEleTags, msgData(3));
	    
	    if (theNodeTags != 0)
	      delete theNodeTags;
	    if (theEleTags != 0)
	      delete theEleTags;

	    this->sendID(msgData);

	    break;	    	    	    	    

	  case ShadowActorSubdomain_applyLoad:
	    this->recvVector(theVect);	    
	    this->applyLoad(theVect(0));
	    break;

	  case ShadowActorSubdomain_setCommittedTime:
	    this->recvVector(theVect);	    
	    this->setCurrentTime(theVect(0));
	    this->setCommittedTime(theVect(0));
	    break;	    
	    
	  case ShadowActorSubdomain_setLoadConstant:
	    this->setLoadConstant();
	    break;	    

	  case ShadowActorSubdomain_update:
	    this->update();
	    break;

	  case ShadowActorSubdomain_updateTimeDt:
	    this->updateTimeDt();
	    break;

	  case ShadowActorSubdomain_computeNodalResponse:
	    tag = msgData(1);
	    if (lastResponse == 0)
		lastResponse = new Vector(tag);
	    else if (lastResponse->Size() != tag) {
		delete lastResponse;
		lastResponse = new Vector(tag);
	    }
	    this->recvVector(*lastResponse);
	    this->computeNodalResponse();
            break;

	  case ShadowActorSubdomain_record:
	    this->record();
	    break;
	    
	  case ShadowActorSubdomain_commit:
	    this->commit();
	    break;
	    
	  case ShadowActorSubdomain_revertToLastCommit:
	    this->revertToLastCommit();
	    break;	    
	    
	  case ShadowActorSubdomain_revertToStart:
	    this->revertToStart();
	    this->sendID(msgData);

	    break;	    	    

	  case ShadowActorSubdomain_addRecorder:
	    theType = msgData(1);
	    theRecorder = theBroker->getPtrNewRecorder(theType);
	    if (theRecorder != 0) {
	      this->recvObject(*theRecorder);	      
	      this->addRecorder(*theRecorder);
	    }
	    break;	    	    

	  case ShadowActorSubdomain_removeRecorders:
	    this->removeRecorders();
	    this->barrierCheck(1);
	    break;	    	    

	  case ShadowActorSubdomain_removeRecorder:
	    theType = msgData(1);
	    this->removeRecorder(theType);
	    break;	    	    
	    

	case ShadowActorSubdomain_wipeAnalysis:
	  this->wipeAnalysis();	    
	  break;

	  case ShadowActorSubdomain_setDomainDecompAnalysis:
	    theType = msgData(1);
	    theDDAnalysis = 
		theBroker->getNewDomainDecompAnalysis(theType, *this);

	    if (theDDAnalysis != 0) {
		this->recvObject(*theDDAnalysis);
		this->setDomainDecompAnalysis(*theDDAnalysis);
		msgData(0) = 0;
	    } else
		msgData(0) = -1;
	    
	    break;

	case ShadowActorSubdomain_setAnalysisAlgorithm:
	  theType = msgData(1);
	  theAlgorithm = theBroker->getNewEquiSolnAlgo(theType);

	  if (theAlgorithm != 0) {
	    this->recvObject(*theAlgorithm);
	    this->setAnalysisAlgorithm(*theAlgorithm);
	    msgData(0) = 0;
	  } else
	    msgData(0) = -1;
	    
	  break;
	  
	case ShadowActorSubdomain_setAnalysisIntegrator:
	  theType = msgData(1);
	  theIntegrator = theBroker->getNewIncrementalIntegrator(theType);
	  if (theIntegrator != 0) {
	    this->recvObject(*theIntegrator);
	    this->setAnalysisIntegrator(*theIntegrator);
	    msgData(0) = 0;
	  } else
	    msgData(0) = -1;
	  this->sendID(msgData);
	  break;

	case ShadowActorSubdomain_setAnalysisLinearSOE:
	  theType = msgData(1);
	  theSOE = theBroker->getNewLinearSOE(theType);

	  if (theSOE != 0) {
	    this->recvObject(*theSOE);
	    this->setAnalysisLinearSOE(*theSOE);
	    msgData(0) = 0;
	  } else
	    msgData(0) = -1;
	    
	  break;

	case ShadowActorSubdomain_setAnalysisEigenSOE:
	  theType = msgData(1);
	  theEigenSOE = theBroker->getNewEigenSOE(theType);

	  if (theEigenSOE != 0) {
	    this->recvObject(*theEigenSOE);
	    this->setAnalysisEigenSOE(*theEigenSOE);
	    msgData(0) = 0;
	  } else
	    msgData(0) = -1;
	    
	  break;

	case ShadowActorSubdomain_setAnalysisConvergenceTest:
	  theType = msgData(1);
	  theTest = theBroker->getNewConvergenceTest(theType);
	  
	  if (theTest != 0) {
	    this->recvObject(*theTest);
	    this->setAnalysisConvergenceTest(*theTest);
	    msgData(0) = 0;
	  } else
	    msgData(0) = -1;

	  break;
	    
	  case ShadowActorSubdomain_domainChange:
	    this->domainChange();

	    tag = this->getNumDOF();
	    if (tag != 0) {
	      if (lastResponse == 0)
		lastResponse = new Vector(tag);
	      else if (lastResponse->Size() != tag) {
		delete lastResponse;
		lastResponse = new Vector(tag);
	      }
	    }
	    break;

	  case ShadowActorSubdomain_getDomainChangeFlag:
	    change = this->getDomainChangeFlag();
	    if (change == true)
	      msgData(0) = 0;
	    else
	      msgData(0) = 1;
	    this->sendID(msgData);
	    
	    break;

	  case ShadowActorSubdomain_clearAnalysis:
//	    this->clearAnalysis();
	    break;
	  /*
	  case 50:
	    const Matrix *theMatrix1 = &(this->getStiff());
	    this->sendMatrix(*theMatrix1);
	    break;

	  case 51:
	    const Matrix *theMatrix2 = &(this->getDamp());
	    this->sendMatrix(*theMatrix2);
	    break;
	    
	  case 52:
	    const Matrix *theMatrix3 = &(this->getMass());
	    this->sendMatrix(*theMatrix3);
	    break;	    
	    */
	  case  ShadowActorSubdomain_getTang:
	    theMatrix = &(this->getTang());
	    this->sendMatrix(*theMatrix);
	    break;	    
	    
	  case ShadowActorSubdomain_getResistingForce:
	    theVector = &(this->getResistingForce());
	    this->sendVector(*theVector);
	    break;	    	    

	  case ShadowActorSubdomain_computeTang:
	    tag = msgData(1);
	    this->setTag(tag);
	    this->computeTang();
	    break;


	  case ShadowActorSubdomain_computeResidual:
	    this->computeResidual();
	    break;

	  case ShadowActorSubdomain_clearAll:
	    this->clearAll();
	    this->sendID(msgData);
	    break;

	  case ShadowActorSubdomain_getNodeDisp:
	    tag = msgData(1);  // nodeTag
	    dbTag = msgData(2); // dof
	    doubleRes = this->getNodeDisp(tag, dbTag, intRes);
	    msgData(0) = intRes;
	    this->sendID(msgData);
	    if (intRes == 0) {
	      theV = new Vector(1);
	      (*theV)(0) = doubleRes;
	      this->sendVector(*theV);
	      delete theV;
	    }
	    break;

	  case ShadowActorSubdomain_setMass:
	    tag = msgData(1);  // nodeTag
	    dbTag = msgData(2); // noRows
	    theOtherType = msgData(3); // noRows
	    theM = new Matrix(dbTag, theOtherType);
	    this->recvMatrix(*theM);
	    intRes = this->setMass(*theM, tag);
	    
	    delete theM;
	    msgData(0) = intRes;
	    this->sendID(msgData);
	    break;


	  case ShadowActorSubdomain_getNodeResponse:
	    tag = msgData(1);  // nodeTag
	    nodeResponseType = (NodeResponseType)msgData(2); 
	    theVector = this->getNodeResponse(tag, nodeResponseType);

	    if (theVector == 0)
	      msgData(0) = 0;
	    else {
	      msgData(0) = 1;
	      msgData(1) = theVector->Size();
	    }
	    this->sendID(msgData);

	    if (theVector != 0)
	      this->sendVector(*theVector);

	    break;

	  case ShadowActorSubdomain_getElementResponse:
	    tag = msgData(1);  // eleTag
	    argc = msgData(2);
	    msgLength = msgData(3);

	    if (msgLength == 0) {
	      opserr << "ElementRecorder::recvSelf() - 0 sized string for responses\n";
	      return -1;
	    }

	    allResponseArgs = new char[msgLength];
	    if (allResponseArgs == 0) {
	      opserr << "ElementRecorder::recvSelf() - out of memory\n";
	      return -1;
	    }

	    theMessage.setData(allResponseArgs, msgLength);
	    if (this->recvMessage(theMessage) < 0) {
	      opserr << "ElementRecorder::recvSelf() - failed to recv message\n";
	      return -1;
	    }

	    //
	    // now break this single array into many
	    // 
	    
	    argv = new char *[argc];
	    if (argv == 0) {
	      opserr << "ElementRecorder::recvSelf() - out of memory\n";
	      return -1;
	    }
	    
	    currentLoc = allResponseArgs;
	    for (int j=0; j<argc; j++) {
	      argv[j] = currentLoc;	      
	      argLength = strlen(currentLoc)+1;
	      currentLoc += argLength;
	    }

	    theVector = this->getElementResponse(tag, (const char**)argv, argc);

	    delete [] argv;
	    delete [] allResponseArgs;

	    if (theVector == 0) 
	      msgData(0) = 0;
	    else {
	      msgData(0) = 1;
	      msgData(1) = theVector->Size();
	    }
	    this->sendID(msgData);

	    if (theVector != 0)
	      this->sendVector(*theVector);
      
	    break;

	  case ShadowActorSubdomain_calculateNodalReactions:
	    if (msgData(0) == 0)
	      this->calculateNodalReactions(true);
	    else
	      this->calculateNodalReactions(false);
	    break;

         case ShadowActorSubdomain_setRayleighDampingFactors:
	   theV = new Vector(4);
	   this->recvVector(*theV);
	   intRes = this->Subdomain::setRayleighDampingFactors((*theV)(0), (*theV)(1), (*theV)(2), (*theV)
(3));
	   delete theV;
	   break;


         case ShadowActorSubdomain_addParameter:
	    theType = msgData(1);
	    dbTag = msgData(2);

	    theParameter = theBroker->getParameter(theType);

	    if (theParameter != 0) {
		theParameter->setDbTag(dbTag);		
		this->recvObject(*theParameter);
		//bool result = true;
		bool result = this->addParameter(theParameter);
		if (result == true)
		    msgData(0) = 0;
		else {
		  opserr << "Actor::addParameter - FAILED\n";
		  msgData(0) = -1;
		}
	    } else
		msgData(0) = -1;

	   break;

       case ShadowActorSubdomain_removeParameter:
	   theType = msgData(1);
	  
	   this->removeParameter(theType);
	 
	    this->sendID(msgData);
	   break;

         case ShadowActorSubdomain_updateParameterINT:
	   theType = msgData(1);  // tag
	   dbTag = msgData(2);    // value

	   msgData(0) = this->Domain::updateParameter(theType, dbTag);
	   this->sendID(msgData);
	   break;

       case ShadowActorSubdomain_updateParameterDOUBLE:
	   theType = msgData(1);  // tag
	 
	   this->recvVector(theVect1);
	
	   msgData(0) = this->Domain::updateParameter(theType, theVect1(0));
	  
	   this->sendID(msgData);
	   break;


	  case ShadowActorSubdomain_DIE:
	    exitYet = true;
	    break;

	  default:
	    opserr << "ActorSubdomain::invalid action " << action << "received\n";
	    msgData(0) = -1;
	    
      }
      //      opserr << "DONE ACTION: " << action << endln;
    }

    //    this->sendID(msgData);
    return 0;
}
Exemple #16
0
void Firewall::filterIncomingMessage(Chat chat, Contact sender, QString &message, time_t time, bool &ignore)
{
    Q_UNUSED(time)

    Account account = chat.chatAccount();

    Protocol *protocol = account.protocolHandler();
    if (!protocol)
        return;

// emotikony s± sprawdzane nawet przy ³±czeniu
    const int min_interval_notify = 2000;

    if (CheckFloodingEmoticons)
    {
        if ((!EmoticonsAllowKnown || sender.ownerBuddy().isAnonymous()) && checkEmoticons(message))
        {
            ignore = true;
            if (LastNotify.elapsed() > min_interval_notify)
            {
                FirewallNotification::notify(chat, sender, tr("flooding DoS attack with emoticons!"));

                writeLog(sender, message);

                LastNotify.restart();
            }
            kdebugf2();
            return;
        }
    }

// atak floodem
    if (checkFlood())
    {
        ignore = true;
        if (LastNotify.elapsed() > min_interval_notify)
        {
            FirewallNotification::notify(chat, sender, tr("flooding DoS attack!"));

            writeLog(sender, message);

            LastNotify.restart();
        }
        kdebugf2();
        return;
    }

// ochrona przed anonimami
    if (checkChat(chat, sender, message, ignore))
        ignore = true;

// ochrona przed konferencjami
    if (checkConference(chat))
        ignore = true;

// wiadomosc zatrzymana. zapisz do loga i wyswietl dymek
    if (ignore)
    {
        if (message.length() > 50)
            FirewallNotification::notify(chat, sender, message.left(50).append("..."));
        else
            FirewallNotification::notify(chat, sender, message);

        writeLog(sender, message);

        if (WriteInHistory)
        {
            if (History::instance()->currentStorage())
            {
                Message msg = Message::create();
                msg.setContent(message);
                msg.setType(Message::TypeReceived);
                msg.setReceiveDate(QDateTime::currentDateTime());
                msg.setSendDate(QDateTime::fromTime_t(time));
                History::instance()->currentStorage()->appendMessage(msg);
            }
        }
    }

    kdebugf2();
}
Exemple #17
0
	void BaseRpcChannel::copyMessage( Message& dest, const Message& src ) {
		if( dest.GetDescriptor() == src.GetDescriptor() ) {
			dest.CopyFrom( src );
		}
	}
Exemple #18
0
int SCI_Poll(int timeout)
{
    if (gCtrlBlock->getMyRole() == CtrlBlock::INVALID)
        return SCI_ERR_UNINTIALIZED;
    
    if (gCtrlBlock->getMyRole() == CtrlBlock::AGENT)
        return SCI_ERR_INVALID_CALLER;

    sci_mode_t mode;
    if (gCtrlBlock->getMyRole() == CtrlBlock::FRONT_END)
        mode = gCtrlBlock->getEndInfo()->fe_info.mode;
    else
        mode = gCtrlBlock->getEndInfo()->be_info.mode;
    if (mode != SCI_POLLING)
        return SCI_ERR_MODE;
/*
    if (gCtrlBlock->getPollQueue()->getSize() == 0) {
        // no messages in the polling queue
        // TODO
        return SCI_ERR_POLL_INVALID;
    }
*/
    int rc = SCI_SUCCESS;
    rc = gCtrlBlock->checkChildHealthState();
    if (rc != SCI_SUCCESS)
        return rc;

    Message *msg = gCtrlBlock->getPollQueue()->consume(timeout);
    if (msg) {
        switch(msg->getType()) {
            case Message::COMMAND:
            case Message::DATA:
                try {
                    gHndlr(gParam, msg->getGroup(), msg->getContentBuf(), msg->getContentLen());
                } catch (...) {
                    // TODO
                }

                gCtrlBlock->getObserver()->unnotify();
                break;
            case Message::INVALID_POLL:
                rc = SCI_ERR_POLL_INVALID;
                gCtrlBlock->getObserver()->unnotify();
                break;
            case Message::SOCKET_BROKEN:
                rc = SCI_ERR_CHILD_BROKEN;
                log_debug("SCI_Poll: received msg SOCKET_BROKEN");
                gCtrlBlock->getObserver()->unnotify();
                break;
            case Message::ERROR_DATA:
                rc = SCI_ERR_DATA;
                log_debug("SCI_Poll: received msg ERROR_DATA");
                gCtrlBlock->getObserver()->unnotify();
                break;
            case Message::ERROR_THREAD:
                rc = SCI_ERR_THREAD;
                log_debug("SCI_Poll: received msg ERROR_THREAD");
                gCtrlBlock->getObserver()->unnotify();
                break;
            default:
                rc = SCI_ERR_UNKNOWN_INFO;
                log_error("SCI_Poll: received unknown command");
                gCtrlBlock->getObserver()->unnotify();
                break;
        }

        gCtrlBlock->getPollQueue()->remove();
    } else {
        rc = SCI_ERR_POLL_TIMEOUT;
    }

    return rc;
}
Exemple #19
0
result_t BusHandler::handleSymbol()
{
	long timeout = SYN_TIMEOUT;
	unsigned char sendSymbol = ESC;
	bool sending = false;
	BusRequest* startRequest = NULL;

	// check if another symbol has to be sent and determine timeout for receive
	switch (m_state)
	{
	case bs_noSignal:
		timeout = m_generateSynInterval>0 ? m_generateSynInterval : SIGNAL_TIMEOUT;
		break;

	case bs_skip:
		timeout = SYN_TIMEOUT;
		break;

	case bs_ready:
		if (m_currentRequest != NULL) {
			setState(bs_ready, RESULT_ERR_TIMEOUT); // just to be sure an old BusRequest is cleaned up
		} else if (m_remainLockCount == 0) {
			startRequest = m_nextRequests.peek();
			if (startRequest == NULL && m_pollInterval > 0) { // check for poll/scan
				time_t now;
				time(&now);
				if (m_lastPoll == 0 || difftime(now, m_lastPoll) > m_pollInterval) {
					Message* message = m_messages->getNextPoll();
					if (message != NULL) {
						m_lastPoll = now;
						PollRequest* request = new PollRequest(message);
						result_t ret = request->prepare(m_ownMasterAddress);
						if (ret != RESULT_OK) {
							logError(lf_bus, "prepare poll message: %s", getResultCode(ret));
							delete request;
						} else {
							startRequest = request;
							m_nextRequests.push(request);
						}
					}
				}
			}
			if (startRequest != NULL) { // initiate arbitration
				sendSymbol = m_ownMasterAddress;
				sending = true;
			}
		}
		break;

	case bs_recvCmd:
	case bs_recvCmdAck:
		timeout = m_slaveRecvTimeout;
		break;

	case bs_recvRes:
		if (m_response.size() > 0 || m_slaveRecvTimeout > SYN_TIMEOUT)
			timeout = m_slaveRecvTimeout;
		else
			timeout = SYN_TIMEOUT;
		break;

	case bs_recvResAck:
		timeout = m_slaveRecvTimeout+m_transferLatency;
		break;

	case bs_sendCmd:
		if (m_currentRequest != NULL) {
			sendSymbol = m_currentRequest->m_master[m_nextSendPos]; // escaped command
			sending = true;
		}
		break;

	case bs_sendResAck:
		if (m_currentRequest != NULL) {
			sendSymbol = m_responseCrcValid ? ACK : NAK;
			sending = true;
		}
		break;

	case bs_sendCmdAck:
		if (m_answer) {
			sendSymbol = m_commandCrcValid ? ACK : NAK;
			sending = true;
		}
		break;

	case bs_sendRes:
		if (m_answer) {
			sendSymbol = m_response[m_nextSendPos]; // escaped response
			sending = true;
		}
		break;

	case bs_sendSyn:
		sendSymbol = SYN;
		sending = true;
		break;
	}

	// send symbol if necessary
	result_t result;
	if (sending) {
		result = m_device->send(sendSymbol);
		if (result == RESULT_OK) {
			if (m_state == bs_ready)
				timeout = m_transferLatency+m_busAcquireTimeout;
			else
				timeout = m_transferLatency+SEND_TIMEOUT;
		} else {
			sending = false;
			timeout = SYN_TIMEOUT;
			if (startRequest != NULL && m_nextRequests.remove(startRequest)) {
				m_currentRequest = startRequest; // force the failed request to be notified
			}
			setState(bs_skip, result);
		}
	}

	// receive next symbol (optionally check reception of sent symbol)
	unsigned char recvSymbol;
	result = m_device->recv(timeout+m_transferLatency, recvSymbol);

	if (!sending && result == RESULT_ERR_TIMEOUT && m_generateSynInterval > 0
	&& timeout >= m_generateSynInterval && (m_state == bs_noSignal || m_state == bs_skip)) {
		// check if acting as AUTO-SYN generator is required
		result = m_device->send(SYN);
		if (result == RESULT_OK) {
			recvSymbol = ESC;
			result = m_device->recv(SEND_TIMEOUT, recvSymbol);
			if (result == RESULT_ERR_TIMEOUT) {
				return setState(bs_noSignal, result);
			}
			if (result != RESULT_OK)
				logError(lf_bus, "unable to receive sent AUTO-SYN symbol: %s", getResultCode(result));
			else if (recvSymbol != SYN) {
				logError(lf_bus, "received %2.2x instead of AUTO-SYN symbol", recvSymbol);
			} else {
				if (m_generateSynInterval != SYN_TIMEOUT) {
					// received own AUTO-SYN symbol back again: act as AUTO-SYN generator now
					m_generateSynInterval = SYN_TIMEOUT;
					logNotice(lf_bus, "acting as AUTO-SYN generator");
				}
				m_remainLockCount = 0;
				return setState(bs_ready, result);
			}
		}
		return setState(bs_skip, result);
	}
	time_t now;
	time(&now);
	if (result != RESULT_OK) {
		if (sending && startRequest != NULL && m_nextRequests.remove(startRequest)) {
			m_currentRequest = startRequest; // force the failed request to be notified
		}
		if ((m_generateSynInterval != SYN_TIMEOUT && difftime(now, m_lastReceive) > 1) // at least one full second has passed since last received symbol
			|| m_state == bs_noSignal)
			return setState(bs_noSignal, result);

		return setState(bs_skip, result);
	}

	m_lastReceive = now;
	if ((recvSymbol == SYN) && (m_state != bs_sendSyn)) {
		if (!sending && m_remainLockCount > 0 && m_command.size() != 1)
			m_remainLockCount--;
		else if (!sending && m_remainLockCount == 0 && m_command.size() == 1)
			m_remainLockCount = 1; // wait for next AUTO-SYN after SYN / address / SYN (bus locked for own priority)

		return setState(bs_ready, m_state == bs_skip ? RESULT_OK : RESULT_ERR_SYN);
	}

	unsigned int headerLen, crcPos;

	switch (m_state)
	{
	case bs_noSignal:
		return setState(bs_skip, RESULT_OK);

	case bs_skip:
		return RESULT_OK;

	case bs_ready:
		if (startRequest != NULL && sending) {
			if (!m_nextRequests.remove(startRequest)) {
				// request already removed (e.g. due to timeout)
				return setState(bs_skip, RESULT_ERR_TIMEOUT);
			}
			m_currentRequest = startRequest;
			// check arbitration
			if (recvSymbol == sendSymbol) { // arbitration successful
				m_nextSendPos = 1;
				m_repeat = false;
				return setState(bs_sendCmd, RESULT_OK);
			}
			// arbitration lost. if same priority class found, try again after next AUTO-SYN
			m_remainLockCount = isMaster(recvSymbol) ? 2 : 1; // number of SYN to wait for before next send try
			if ((recvSymbol & 0x0f) != (sendSymbol & 0x0f) && m_lockCount > m_remainLockCount)
				// if different priority class found, try again after N AUTO-SYN symbols (at least next AUTO-SYN)
				m_remainLockCount = m_lockCount;
			setState(m_state, RESULT_ERR_BUS_LOST); // try again later
		}
		result = m_command.push_back(recvSymbol, false); // expect no escaping for master address
		if (result < RESULT_OK)
			return setState(bs_skip, result);

		m_repeat = false;
		return setState(bs_recvCmd, RESULT_OK);

	case bs_recvCmd:
		headerLen = 4;
		crcPos = m_command.size() > headerLen ? headerLen + 1 + m_command[headerLen] : 0xff; // header symbols are never escaped
		result = m_command.push_back(recvSymbol, true, m_command.size() < crcPos);
		if (result < RESULT_OK)
			return setState(bs_skip, result);

		if (result == RESULT_OK && crcPos != 0xff && m_command.size() == crcPos + 1) { // CRC received
			unsigned char dstAddress = m_command[1];
			m_commandCrcValid = m_command[headerLen + 1 + m_command[headerLen]] == m_command.getCRC(); // header symbols are never escaped
			if (m_commandCrcValid) {
				if (dstAddress == BROADCAST) {
					receiveCompleted();
					return setState(bs_skip, RESULT_OK);
				}
				addSeenAddress(m_command[0]);
				if (m_answer
				        && (dstAddress == m_ownMasterAddress || dstAddress == m_ownSlaveAddress))
					return setState(bs_sendCmdAck, RESULT_OK);

				return setState(bs_recvCmdAck, RESULT_OK);
			}
			if (dstAddress == BROADCAST)
				return setState(bs_skip, RESULT_ERR_CRC);

			if (m_answer
			        && (dstAddress == m_ownMasterAddress || dstAddress == m_ownSlaveAddress)) {
				return setState(bs_sendCmdAck, RESULT_ERR_CRC);
			}
			if (m_repeat)
				return setState(bs_skip, RESULT_ERR_CRC);
			return setState(bs_recvCmdAck, RESULT_ERR_CRC);
		}
		return RESULT_OK;

	case bs_recvCmdAck:
		if (recvSymbol == ACK) {
			if (!m_commandCrcValid)
				return setState(bs_skip, RESULT_ERR_ACK);

			if (m_currentRequest != NULL) {
				if (isMaster(m_currentRequest->m_master[1])) {
					return setState(bs_sendSyn, RESULT_OK);
				}
			}
			else if (isMaster(m_command[1])) { // header symbols are never escaped
				receiveCompleted();
				return setState(bs_skip, RESULT_OK);
			}

			m_repeat = false;
			return setState(bs_recvRes, RESULT_OK);
		}
		if (recvSymbol == NAK) {
			if (!m_repeat) {
				m_repeat = true;
				m_nextSendPos = 0;
				m_command.clear();
				if (m_currentRequest != NULL)
					return setState(bs_sendCmd, RESULT_ERR_NAK, true);

				return setState(bs_recvCmd, RESULT_ERR_NAK);
			}

			return setState(bs_skip, RESULT_ERR_NAK);
		}

		return setState(bs_skip, RESULT_ERR_ACK);

	case bs_recvRes:
		headerLen = 0;
		crcPos = m_response.size() > headerLen ? headerLen + 1 + m_response[headerLen] : 0xff;
		result = m_response.push_back(recvSymbol, true, m_response.size() < crcPos);
		if (result < RESULT_OK)
			return setState(bs_skip, result);

		if (result == RESULT_OK && crcPos != 0xff && m_response.size() == crcPos + 1) { // CRC received
			m_responseCrcValid = m_response[headerLen + 1 + m_response[headerLen]] == m_response.getCRC();
			if (m_responseCrcValid) {
				if (m_currentRequest != NULL)
					return setState(bs_sendResAck, RESULT_OK);

				return setState(bs_recvResAck, RESULT_OK);
			}
			if (m_repeat) {
				if (m_currentRequest != NULL)
					return setState(bs_sendSyn, RESULT_ERR_CRC);

				return setState(bs_skip, RESULT_ERR_CRC);
			}
			if (m_currentRequest != NULL)
				return setState(bs_sendResAck, RESULT_ERR_CRC);

			return setState(bs_recvResAck, RESULT_ERR_CRC);
		}
		return RESULT_OK;

	case bs_recvResAck:
		if (recvSymbol == ACK) {
			if (!m_responseCrcValid)
				return setState(bs_skip, RESULT_ERR_ACK);

			receiveCompleted();
			return setState(bs_skip, RESULT_OK);
		}
		if (recvSymbol == NAK) {
			if (!m_repeat) {
				m_repeat = true;
				m_response.clear();
				return setState(bs_recvRes, RESULT_ERR_NAK, true);
			}
			return setState(bs_skip, RESULT_ERR_NAK);
		}
		return setState(bs_skip, RESULT_ERR_ACK);

	case bs_sendCmd:
		if (m_currentRequest != NULL && sending && recvSymbol == sendSymbol) {
			// successfully sent
			m_nextSendPos++;
			if (m_nextSendPos >= m_currentRequest->m_master.size()) {
				// master data completely sent
				if (m_currentRequest->m_master[1] == BROADCAST)
					return setState(bs_sendSyn, RESULT_OK);

				m_commandCrcValid = true;
				return setState(bs_recvCmdAck, RESULT_OK);
			}
			return RESULT_OK;
		}
		return setState(bs_skip, RESULT_ERR_INVALID_ARG);

	case bs_sendResAck:
		if (m_currentRequest != NULL && sending && recvSymbol == sendSymbol) {
			// successfully sent
			if (!m_responseCrcValid) {
				if (!m_repeat) {
					m_repeat = true;
					m_response.clear();
					return setState(bs_recvRes, RESULT_ERR_NAK, true);
				}
				return setState(bs_sendSyn, RESULT_ERR_ACK);
			}
			return setState(bs_sendSyn, RESULT_OK);
		}
		return setState(bs_skip, RESULT_ERR_INVALID_ARG);

	case bs_sendCmdAck:
		if (sending && m_answer && recvSymbol == sendSymbol) {
			// successfully sent
			if (!m_commandCrcValid) {
				if (!m_repeat) {
					m_repeat = true;
					m_command.clear();
					return setState(bs_recvCmd, RESULT_ERR_NAK, true);
				}
				return setState(bs_skip, RESULT_ERR_ACK);
			}
			if (isMaster(m_command[1])) {
				receiveCompleted(); // decode command and store value
				return setState(bs_skip, RESULT_OK);
			}

			m_nextSendPos = 0;
			m_repeat = false;
			Message* message;
			istringstream input; // TODO create input from database of internal variables
			message = m_messages->find(m_command);
			if (message == NULL) {
				message = m_messages->find(m_command, true);
				if (message!=NULL && message->getSrcAddress()!=SYN)
					message = NULL;
			}
			if (message == NULL || message->isWrite())
				return setState(bs_skip, RESULT_ERR_INVALID_ARG); // don't know this request or definition has wrong direction, deny
			if (message == m_messages->getScanMessage(m_ownSlaveAddress)) {
				input.str(SCAN_ANSWER);
			}

			// build response and store in m_response for sending back to requesting master
			m_response.clear(true); // escape while sending response
			result = message->prepareSlave(input, m_response);
			if (result != RESULT_OK)
				return setState(bs_skip, result);
			return setState(bs_sendRes, RESULT_OK);
		}
		return setState(bs_skip, RESULT_ERR_INVALID_ARG);

	case bs_sendRes:
		if (sending && m_answer && recvSymbol == sendSymbol) {
			// successfully sent
			m_nextSendPos++;
			if (m_nextSendPos >= m_response.size()) {
				// slave data completely sent
				return setState(bs_recvResAck, RESULT_OK);
			}
			return RESULT_OK;
		}
		return setState(bs_skip, RESULT_ERR_INVALID_ARG);

	case bs_sendSyn:
		if (sending && recvSymbol == sendSymbol) {
			// successfully sent
			return setState(bs_skip, RESULT_OK);
		}
		return setState(bs_skip, RESULT_ERR_INVALID_ARG);

	}

	return RESULT_OK;
}
			/**
			 * writeMessage will write the message in 2 a-sync writes, 1 for the header and 1 for the body.
			 * After each write a callback will be called that should handle the stuff just read.
			 * After writing the full message handleMessageWritten will be called.
			 *
			 * @see handle_header_written
			 * @see handle_body_written
			 * @see handleMessageWritten
			 */
			void writeMessage( Message& aMessage)
			{
				boost::asio::async_write( getSocket(), boost::asio::buffer( aMessage.getHeader().toString(), aMessage.getHeader().getHeaderLength()), boost::bind( &Session::handleHeaderWritten, this, aMessage, boost::asio::placeholders::error));
			}
Exemple #21
0
void MainWindow::writeTcpData(Message message)
{
    QByteArray data = message.encode();
    this->connectionManager->write(data);
}
			/**
			 * readMessage will read the message in 2 a-sync reads, 1 for the header and 1 for the body.
			 * After each read a callback will be called that should handle the stuff just read.
			 * After reading the full message handleMessageRead will be called
			 * whose responsibility it is to handle the message as a whole.
			 *
			 * @see handle_header_read
			 * @see handle_body_read
			 * @see handleMessageRead
			 */
			void readMessage()
			{
				Message aMessage;
				headerBuffer.resize( aMessage.getHeader().getHeaderLength());
				boost::asio::async_read( getSocket(), boost::asio::buffer( headerBuffer), boost::bind( &Session::handleHeaderRead, this, aMessage, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
			}
Exemple #23
0
int main( int argc, char *argv[] ) {
	cout << "*** ImapLibrary Test ***" << endl;
	cout << "Connect to imap.gmail.com at port 993..." << endl;
	imap_server 	= "imap.gmail.com";					// Nombre servidor IMAP
	port_n			= 993;								// 143 || 993 con encriptación SSL
	cout << "Write your username: "******"Write your pass: "******"********** IMAPLogin **********" << endl;			// DEBUG
	i = IMAPLogin(connection, imap_server, port_n, user, pass, usessl);
	if (i == BAD_LOGIN) {
		printf("Bad login: %d\n", i);
		return -1;
	}
	if (i == SERVER_NOT_READY_FOR_CONNECTION) {
		printf("Server not ready for connection: %d\n", i);
		return -1;
	}
	
	/**
	 * Get folder list from server
	 * - we need to get a list of folder names
	 */
	cout << endl << "********** getIMAPFolders **********" << endl;		// DEBUG
    list<string> folder_names;
    folder_root = ""; // Nombre del buzón de correo que queremos que liste
    int return_code;
    
    return_code = getIMAPFolders(connection, folder_names, folder_root );
    
	cout << endl << "-------------------------------------" << endl;	// DEBUG
	cout << "-----------List of Folders-----------" << endl;			// DEBUG
	cout << "-------------------------------------" << endl;			// DEBUG
	cout << folder_root << "/"<< endl;									// DEBUG
    if( return_code == SUCCESS ) { //  Successful 
        create_folder_list(folder_names);
    }
    
    // DEBUG - Show folder_list
    list<Folder>::iterator itera = folder_list.begin();
    while(itera != folder_list.end()) {
		//cout << "folder: " << (*itera).get_Folder_Name() << endl;
		//cout << "     -> full_name= " << (*itera).get_Full_Folder_Name() << endl;
		//cout << " -> seq_start= " << (*itera).get_Sequence_Start() << endl;
		//cout << " -> seq_stop = " << (*itera).get_Sequence_Stop() << endl;
		//cout << " -> num_mess = " << (*itera).get_Num_Messages() << endl;
		if (strcmp("INBOX", (char*) (*itera).get_Folder_Name().c_str()) == 0)
			break;
		itera++;
	}

	/**
	 * Select a folder
	 * - In order to get the emails of a folder, we must select it before.
	 */
	string folderOpenStatus;
	int numMessages;
	//itera = folder_list.begin();
	cout << endl << "********** SelectFolders **********" << endl;		// DEBUG
	cout << "Folder name: " << (*itera).get_Folder_Name() << endl;		// DEBUG
	cout << "Full folder name: " << (*itera).get_Full_Folder_Name() << endl;// DEBUG
	i = SelectFolder(connection, (*itera).get_Folder_Name(), numMessages, folderOpenStatus);
	if (i == UNKNOWN_MAILBOX)
		printf("Unknown mailbox - %d\n",i);
	cout << "numMessages = " << numMessages << " |folderOpenStatus = " << folderOpenStatus << endl;// DEBUG

	/**
	 * Get new emails
	 * - We must select a folder before or the function return us a failure
	 */
	printf("\n\n********************************************\n");
	cout << "Folder name: " << (*itera).get_Folder_Name() << endl;
	cout << "Full folder name: " << (*itera).get_Folder_Name() << endl;
	i = GetNewMail(connection, (*itera));
	if (i>BEG_FAIL || i==LIST_FAILED || i== FOLDER_NOT_EXIST) {
		printf("GetNewMail Error - %d\n",i);	
		return -1;
	}
	
	int Message_id = 2;		// Message identifier
	Message *email = (*itera).get_Message(Message_id);		// Para obtener cuerpo de un email a partir de su uid,
															// primero necesitamos coger uno de la lista (orden por id)
	if (email != NULL) {
		cout << "From: " << email->get_From_Address() << endl;			// DEBUG
		//cout << "Have body? " << email->have_Body_Text() << endl;		// DEBUG
		//cout << "Date: " << email->get_Date() << endl;					// DEBUG
		cout << "Subject: " << email->get_Subject() << endl;			// DEBUG
		//cout << "UID: " << email->get_UID() << endl;					// DEBUG
		//cout << "-------------------------------" << endl;				// DEBUG
		i=email->get_Body_From_Server(connection);
		//cout << "getbodyfromserver=" << i << endl;						// DEBUG
		//cout << "Have body? " << email->have_Body_Text() << endl;		// DEBUG
		if (email->have_Body_Text() == 1)
			cout << "BODY: " << email->get_Body_Text();					// DEBUG
	} else
		cout << "The message does not exist." << endl;

	/**
	 * Logout
	 * - Finalize the session
	 */
	i = IMAPLogout(connection);
	if (i != SUCCESS) {
		cout << "An error ocurred" << endl;
		return -1;
	}
    
	return 0;
}
Exemple #24
0
/*
 * Author: Chris Pinola
 */
void handleMessage(Message *inm){
	char *cmd = inm->getCmd(); //extract CMD from packet
	char *tmp; // just to hold string tokens
	char *argvNew[8]; // holds onto the various arguments given by the user
	int i = 1; // helps us stay within the array bounds
	Message *m = new Message(); // the message that we'll eventually send back to the client
	
	// run through and split the command string on all spaces
	if((tmp = strtok(cmd, " ")) != NULL){
		argvNew[0] = tmp;
		
		while ((tmp = strtok(NULL, " ")) != NULL){
			if(i < 7){
				argvNew[i] = tmp;
				i++;
			} else{
				break;
			}
		}
		
		argvNew[i] = NULL; //make sure the array is NULL "terminated"
		
		//now the fun part begins
		//each branch corresponds to a different command
		//basically just calls the appropriate database functions
		//and makes fills in our new message object with the
		//response
		if(strcmp(argvNew[0], "locations") == 0){
			char *r = locationsWithMissing();
			//cout << r << endl;
			m->setCmd(r);
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "quit") == 0){
			connected = false;
		} else if(strcmp(argvNew[0], "createmissing") == 0){
			long newID;
			if((newID = createMissing(argvNew[1], argvNew[2], "loc")) <= 0){
				m->setCmd(err);
			} else{
				m->setCmd((char *) newID);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "query") == 0){
			if(queryAdmin(argvNew[1], argvNew[2])){
				m->setCmd("That person has been found!");
			} else{
				m->setCmd("That person has not been found");
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "login") == 0){
			if(auth){
				//already signed in
				m->setCmd("You're already signed in");
			} else{
				u.assign(argvNew[1]);
				if(authenticateUser(argvNew[1], argvNew[2])){
					auth = true;
					m->setCmd("You have successfully signed in!");
				} else{
					m->setCmd("Invalid credentials");
				}
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "adduser") == 0){
			if(auth){
				if(newUser(argvNew[1], argvNew[2])){
					m->setCmd("Successfully added new user");
				} else{
					m->setCmd(err);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "id") == 0){
			if(auth){
				if(positiveID(argvNew[1], argvNew[2], argvNew[3])){
					m->setCmd("Successfully ID'd body");
				} else{
					m->setCmd(err);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "removemissing") == 0){
			if(auth){
				if(removeFromPublic(argvNew[1])){
					m->setCmd("Successfully removed entry");
				} else{
					m->setCmd(err);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "removebody") == 0){
			if(auth){
				if(removeFromAdmin(argvNew[1])){
					m->setCmd("Successfully removed entry");
				} else{
					m->setCmd(err);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "password") == 0){
			if(auth){
				if(changePassword(u.c_str(), argvNew[1], argvNew[2])){
					char *pwdsuc = "Successfully changed password";
					cout << pwdsuc << endl;
					m->setCmd(pwdsuc);
				} else{
					char *pwderr = "Either the given username does not exist, or the old password doesn't match for that user.";
					cout << pwderr << endl;
					m->setCmd(pwderr);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "createbody") == 0){
			if(auth){
				if((argvNew[3] != NULL) && (argvNew[4] != NULL)){
					// full command
					if(createMissingAdmin(argvNew[1], argvNew[2], argvNew[3], argvNew[4])){
						m->setCmd("Successfully added entry");
					} else{
						m->setCmd(err);
					}
				} else{
					// no name given
					if(createMissingAdmin(argvNew[1], argvNew[2], NULL, NULL)){
						m->setCmd("Successfully added entry");
					} else{
						m->setCmd(err);
					}
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "dlmissingphoto") == 0){
			if(auth){
				long s;
				m->setImg(getPhotoPublic(argvNew[1], &s), s);
				m->setCmd("Successfully retrieved photo!");
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "addphoto") == 0){
			if(addPhotoPublic(argvNew[1], inm->getContent(), inm->getContentSize())){
				m->setCmd("Successfully added photo");
			} else{
				m->setCmd(err);
			}
			nl -> FromApplicationLayer(m);
		} else if(strcmp(argvNew[0], "addbodyphoto") == 0){
			if(auth){
				if(addPhotoAdmin(argvNew[1], inm->getContent(), inm->getContentSize())){
					m->setCmd("Successfully added photo");
				} else{
					m->setCmd(err);
				}
			} else{
				m->setCmd(nauth);
			}
			nl -> FromApplicationLayer(m);
		} else{
			cerr << "Server received unrecognized command: " << cmd << endl;
		}
	}
}
void DSPEngine::handleMessages()
{
	Message* message;
	while((message = m_messageQueue.accept()) != NULL) {
		qDebug("Message: %s", message->getIdentifier());

		if(DSPPing::match(message)) {
			message->completed(m_state);
		} else if(DSPExit::match(message)) {
			gotoIdle();
			m_state = StNotStarted;
			exit();
			message->completed(m_state);
		} else if(DSPAcquisitionStart::match(message)) {
			m_state = gotoIdle();
			if(m_state == StIdle)
				m_state = gotoRunning();
			message->completed(m_state);
		} else if(DSPAcquisitionStop::match(message)) {
			m_state = gotoIdle();
			message->completed(m_state);
		} else if(DSPGetDeviceDescription::match(message)) {
			((DSPGetDeviceDescription*)message)->setDeviceDescription(m_deviceDescription);
			message->completed();
		} else if(DSPGetErrorMessage::match(message)) {
			((DSPGetErrorMessage*)message)->setErrorMessage(m_errorMessage);
			message->completed();
		} else if(DSPSetSource::match(message)) {
			handleSetSource(((DSPSetSource*)message)->getSampleSource());
			message->completed();
		} else if(DSPAddSink::match(message)) {
			SampleSink* sink = ((DSPAddSink*)message)->getSampleSink();
			if(m_state == StRunning) {
				DSPSignalNotification* signal = DSPSignalNotification::create(m_sampleRate, 0, m_tunerFrequency);
				signal->submit(&m_messageQueue, sink);
				sink->start();
			}
			m_sampleSinks.push_back(sink);
			message->completed();
		} else if(DSPRemoveSink::match(message)) {
			SampleSink* sink = ((DSPAddSink*)message)->getSampleSink();
			if(m_state == StRunning)
				sink->stop();
			m_sampleSinks.remove(sink);
			message->completed();
		} else if(DSPAddAudioSource::match(message)) {
			m_audioOutput.addFifo(((DSPAddAudioSource*)message)->getAudioFifo());
			message->completed();
		} else if(DSPRemoveAudioSource::match(message)) {
			m_audioOutput.removeFifo(((DSPAddAudioSource*)message)->getAudioFifo());
			message->completed();
		} else if(DSPConfigureCorrection::match(message)) {
			DSPConfigureCorrection* conf = (DSPConfigureCorrection*)message;
			m_iqImbalanceCorrection = conf->getIQImbalanceCorrection();
			if(m_dcOffsetCorrection != conf->getDCOffsetCorrection()) {
				m_dcOffsetCorrection = conf->getDCOffsetCorrection();
				m_iOffset = 0;
				m_qOffset = 0;
			}
			if(m_iqImbalanceCorrection != conf->getIQImbalanceCorrection()) {
				m_iqImbalanceCorrection = conf->getIQImbalanceCorrection();
				m_iRange = 1 << 16;
				m_qRange = 1 << 16;
				m_imbalance = 65536;
			}
			message->completed();
		} else {
			if(!distributeMessage(message))
				message->completed();
		}
	}
}
Exemple #26
0
void MessageController::setStuff()
{
  //  theMessages.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Add remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\"><PatientList><Patient firstName=\"Jon\" lastName=\"Doe\" healthCardNumber=\"4444333222\" dateAdmitted=\"1920-03-02T11:15:32\" dateAdded=\"1920-03-02T11:15:32\" reqCare=\"1\" occCare=\"1\"/></PatientList></Facility></Area></Add>");
  //  theMessages.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Add remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\" CCC=\"10\"/></Area></Add>");

    /*    theMessages.append("test2");
    theMessages.append("test3");
    theMessages.append("test4");
    theMessages.append("test5");
    theMessages.append("test10");*/


    Message * message = new Message;

 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Add remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\"><PatientList><Patient firstName=\"Jon\" lastName=\"Doe\" healthCardNumber=\"4444333222\" dateAdmitted=\"1920-03-02T11:15:32\" dateAdded=\"1920-03-02T11:15:32\" reqCare=\"1\" occCare=\"1\"/></PatientList></Facility></Area></Add>");

//    receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Delete remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\"><PatientList><Patient firstName=\"Jon\" lastName=\"Doe\" healthCardNumber=\"4444333222\" dateAdmitted=\"1920-03-02T11:15:32\" dateAdded=\"1920-03-02T11:15:32\" reqCare=\"1\" occCare=\"1\"/></PatientList></Facility></Area></Delete>");


 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Add remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\" CCC=\"10\"/></Area></Add>");

 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Delete remote=\"true\"><Area ID=\"5\"><Facility ID=\"7\" CCC=\"15\"/></Area></Delete>");

 //     receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Add remote=\"true\"><Area ID=\"5\"><WaitingList><Patient firstName=\"Jon\" lastName=\"Doe\" healthCardNumber=\"545687\" dateAdded=\"1920-03-02T11:15:32\" reqCare=\"3\" occCare=\"1\"/></WaitingList></Area></Add>");
 //    receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Delete remote=\"true\"><Area ID=\"5\"><WaitingList><Patient firstName=\"Jon\" lastName=\"Doe\" healthCardNumber=\"545687\" dateAdded=\"1920-03-02T11:15:32\" reqCare=\"3\" occCare=\"1\"/></WaitingList></Area></Delete>");


 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Request ID=\"2705\"><Report startDate=\"2002-05-30T09:00:00\" endDate=\"1994-05-30T09:00:00\"><FacilityRecord><Facility ID=\"13\"/><ACRecord occupied=\"500\"/><CCCRecord occupied=\"0\"/><LTCRecord occupied=\"0\"/></FacilityRecord></Report></Request>");
 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Response ID=\"23205\"><Report startDate=\"2002-05-30T09:00:00\" endDate=\"1994-05-30T09:00:00\"><FacilityRecord dateTime=\"2002-05-30T09:00:00\"><Facility ID=\"7\"/><ACRecord occupied=\"0\"/><CCCRecord occupied=\"0\"/><LTCRecord occupied=\"0\"/></FacilityRecord></Report></Response>");


 //   receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Request ID=\"2705\"><Report startDate=\"2002-05-30T09:00:00\" endDate=\"1994-05-30T09:00:00\"><FacilityRecord><Facility ID=\"7\"/><ACRecord occupied=\"25\"/><CCCRecord occupied=\"0\"/><LTCRecord occupied=\"0\"/></FacilityRecord></Report></Request>");

//    receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Response ID=\"2705\"><Report startDate=\"2002-05-30T09:00:00\" endDate=\"1994-05-30T09:00:00\"><FacilityRecord dateTime=\"2002-05-30T09:00:00\"><Facility ID=\"7\"/><ACRecord occupied=\"120\"/></FacilityRecord></Report></Response>");
//    receivedMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><Response ID=\"2705\"><Report startDate=\"2002-05-30T09:00:00\" endDate=\"1994-05-30T09:00:00\"><FacilityRecord dateTime=\"2002-05-30T09:00:00\"><Facility ID=\"12\"/><ACRecord occupied=\"80\"/></FacilityRecord></Report></Response>");



   //qDebug() << "THE REQUEST=============================";
   //QList<QString> qwert;
   //qwert.append("7");
   //QString x =  XMLReader::getInstance()->requestAmountOfBeds(qwert,"1","0","0","1235", "1930-05-30T09:00:00","2011-05-30T09:00:00");
    QString x = XMLReader::getInstance()->rebuild();
    theMessages.append(x);

    //theMessages.append(x);

while(1)
{

   // qDebug()<<  AddFacCtrl::getInstance()->facilityList->size();
    if(!theMessages.isEmpty())
    {
        message->tsend(theMessages.at(0));
        theMessages.removeAt(0);
    }

    message->treceive();


    if(!receivedMessage.isEmpty())
    {
        QString RM = XMLReader::getInstance()->readRequest(receivedMessage.at(0));

        qDebug() << receivedMessage.at(0);
        if (RM == "-1"){}
        else if (RM == "-2"){reportList.append(receivedMessage.at(0));}
        else{
            theMessages.append(RM);
        }
        receivedMessage.removeAt(0);
    }
}



    /*   while(1)
        {
   //     message->treceive();
        if(!theMessages.isEmpty())
        {
            message->tsend(theMessages.at(0));
            theMessages.removeAt(0);
        }
        message->treceive();

        QString answer = XMLReader::getInstance()->readRequest(receivedMessage.at(0));

        //Deal with the head of the received messages //might do it for all messages so it is faster???
        if(!receivedMessage.isEmpty())
        {
            qDebug() << receivedMessage.at(0);
            if(answer == "-2")
            {
                reportList.append(receivedMessage.at(0)); //Add it to the report list

               qDebug()<<"SIZE LIST"<< reportList.size();
            }
            else
            {
                if (answer != "-1")
                {
                    theMessages.append(XMLReader::getInstance()->readRequest(receivedMessage.at(0)));
                }
            }

                receivedMessage.removeAt(0);
        }
    }*/
}
void Client::HandleRetransmissionTimer(void)
{
    uint32_t now = otPlatAlarmGetNow();
    uint32_t nextDelta = 0xffffffff;
    RequestMetadata requestMetadata;
    Message *message = mPendingRequests.GetHead();
    Message *nextMessage = NULL;
    Ip6::MessageInfo messageInfo;

    while (message != NULL)
    {
        nextMessage = message->GetNext();
        requestMetadata.ReadFrom(*message);

        if (requestMetadata.IsLater(now))
        {
            // Calculate the next delay and choose the lowest.
            if (requestMetadata.mNextTimerShot - now < nextDelta)
            {
                nextDelta = requestMetadata.mNextTimerShot - now;
            }
        }
        else if ((requestMetadata.mConfirmable) &&
                 (requestMetadata.mRetransmissionCount < kMaxRetransmit))
        {
            // Increment retransmission counter and timer.
            requestMetadata.mRetransmissionCount++;
            requestMetadata.mRetransmissionTimeout *= 2;
            requestMetadata.mNextTimerShot = now + requestMetadata.mRetransmissionTimeout;
            requestMetadata.UpdateIn(*message);

            // Check if retransmission time is lower than current lowest.
            if (requestMetadata.mRetransmissionTimeout < nextDelta)
            {
                nextDelta = requestMetadata.mRetransmissionTimeout;
            }

            // Retransmit
            if (!requestMetadata.mAcknowledged)
            {
                messageInfo.SetPeerAddr(requestMetadata.mDestinationAddress);
                messageInfo.SetPeerPort(requestMetadata.mDestinationPort);
                messageInfo.SetSockAddr(requestMetadata.mSourceAddress);

                SendCopy(*message, messageInfo);
            }
        }
        else
        {
            // No expected response or acknowledgment.
            FinalizeCoapTransaction(*message, requestMetadata, NULL, NULL, NULL, kThreadError_ResponseTimeout);
        }

        message = nextMessage;
    }

    if (nextDelta != 0xffffffff)
    {
        mRetransmissionTimer.Start(nextDelta);
    }
}
Exemple #28
0
AttachmentParser::Result qm::AttachmentHelper::detach(MessageEnumerator* pEnum,
													  const NameList* pListName)
{
	assert(pSecurityModel_);
	
	unsigned int nSecurityMode = pSecurityModel_->getSecurityMode();
	
	DetachDialog::List list;
	DetachDialogListFree freeList(list);
	while (pEnum->next()) {
		Message msg;
		Message* pMessage = pEnum->getMessage(Account::GMF_TEXT, 0, nSecurityMode, &msg);
		if (!pMessage)
			return AttachmentParser::RESULT_FAIL;
		addItems(*pMessage, pEnum->getMessageHolder(), pListName, &list);
	}
	if (list.empty())
		return AttachmentParser::RESULT_OK;
	
	DetachDialog dialog(pProfile_, list);
	if (dialog.doModal(hwnd_) != IDOK)
		return AttachmentParser::RESULT_CANCEL;
	
	const WCHAR* pwszFolder = dialog.getFolder();
	
	pEnum->reset();
	pEnum->next();
	
	MessageHolder* pmh = 0;
	Message msg;
	Message* pMessage = 0;
	AttachmentParser::AttachmentList l;
	AttachmentParser::AttachmentListFree free(l);
	bool bAddZoneId = isAddZoneId();
	DetachCallbackImpl callback(0, hwnd_);
	unsigned int n = 0;
	for (DetachDialog::List::iterator it = list.begin(); it != list.end(); ++it) {
		if (it == list.begin() || (*it).pmh_ != pmh) {
			pmh = (*it).pmh_;
			while (pEnum->getMessageHolder() != pmh)
				pEnum->next();
			n = 0;
			msg.clear();
			pMessage = 0;
			free.free();
		}
		else {
			++n;
		}
		if ((*it).wstrName_) {
			if (!pMessage) {
				pMessage = pEnum->getMessage(Account::GMF_ALL, 0, nSecurityMode, &msg);
				if (!pMessage)
					return AttachmentParser::RESULT_FAIL;
				AttachmentParser(*pMessage).getAttachments(AttachmentParser::GAF_NONE, &l);
			}
			assert(n < l.size());
			const AttachmentParser::AttachmentList::value_type& v = l[n];
			if (AttachmentParser(*v.second).detach(pwszFolder, (*it).wstrName_,
				bAddZoneId, &callback, 0) == AttachmentParser::RESULT_FAIL)
				return AttachmentParser::RESULT_FAIL;
		}
	}
	
	if (dialog.isOpenFolder())
		openFolder(pwszFolder);
	
	return AttachmentParser::RESULT_OK;
}
Exemple #29
0
std::string runQuery(OperationContext* opCtx,
                     QueryMessage& q,
                     const NamespaceString& nss,
                     Message& result) {
    CurOp& curOp = *CurOp::get(opCtx);
    curOp.ensureStarted();

    uassert(ErrorCodes::InvalidNamespace,
            str::stream() << "Invalid ns [" << nss.ns() << "]",
            nss.isValid());
    invariant(!nss.isCommand());

    // Set CurOp information.
    const auto upconvertedQuery = upconvertQueryEntry(q.query, nss, q.ntoreturn, q.ntoskip);
    beginQueryOp(opCtx, nss, upconvertedQuery, q.ntoreturn, q.ntoskip);

    // Parse the qm into a CanonicalQuery.
    const boost::intrusive_ptr<ExpressionContext> expCtx;
    auto statusWithCQ =
        CanonicalQuery::canonicalize(opCtx,
                                     q,
                                     expCtx,
                                     ExtensionsCallbackReal(opCtx, &nss),
                                     MatchExpressionParser::kAllowAllSpecialFeatures);
    if (!statusWithCQ.isOK()) {
        uasserted(17287,
                  str::stream() << "Can't canonicalize query: "
                                << statusWithCQ.getStatus().toString());
    }
    unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
    invariant(cq.get());

    LOG(5) << "Running query:\n" << redact(cq->toString());
    LOG(2) << "Running query: " << redact(cq->toStringShort());

    // Parse, canonicalize, plan, transcribe, and get a plan executor.
    AutoGetCollectionForReadCommand ctx(opCtx, nss, AutoGetCollection::ViewMode::kViewsForbidden);
    Collection* const collection = ctx.getCollection();

    {
        const QueryRequest& qr = cq->getQueryRequest();

        // Allow the query to run on secondaries if the read preference permits it. If no read
        // preference was specified, allow the query to run iff slaveOk has been set.
        const bool slaveOK = qr.hasReadPref()
            ? uassertStatusOK(ReadPreferenceSetting::fromContainingBSON(q.query))
                  .canRunOnSecondary()
            : qr.isSlaveOk();
        uassertStatusOK(
            repl::ReplicationCoordinator::get(opCtx)->checkCanServeReadsFor(opCtx, nss, slaveOK));
    }

    // We have a parsed query. Time to get the execution plan for it.
    auto exec = uassertStatusOK(getExecutorLegacyFind(opCtx, collection, nss, std::move(cq)));

    const QueryRequest& qr = exec->getCanonicalQuery()->getQueryRequest();

    // If it's actually an explain, do the explain and return rather than falling through
    // to the normal query execution loop.
    if (qr.isExplain()) {
        BufBuilder bb;
        bb.skip(sizeof(QueryResult::Value));

        BSONObjBuilder explainBob;
        Explain::explainStages(
            exec.get(), collection, ExplainOptions::Verbosity::kExecAllPlans, &explainBob);

        // Add the resulting object to the return buffer.
        BSONObj explainObj = explainBob.obj();
        bb.appendBuf((void*)explainObj.objdata(), explainObj.objsize());

        // Set query result fields.
        QueryResult::View qr = bb.buf();
        qr.setResultFlagsToOk();
        qr.msgdata().setLen(bb.len());
        curOp.debug().responseLength = bb.len();
        qr.msgdata().setOperation(opReply);
        qr.setCursorId(0);
        qr.setStartingFrom(0);
        qr.setNReturned(1);
        result.setData(bb.release());
        return "";
    }

    // Handle query option $maxTimeMS (not used with commands).
    if (qr.getMaxTimeMS() > 0) {
        uassert(40116,
                "Illegal attempt to set operation deadline within DBDirectClient",
                !opCtx->getClient()->isInDirectClient());
        opCtx->setDeadlineAfterNowBy(Milliseconds{qr.getMaxTimeMS()});
    }
    opCtx->checkForInterrupt();  // May trigger maxTimeAlwaysTimeOut fail point.

    // Run the query.
    // bb is used to hold query results
    // this buffer should contain either requested documents per query or
    // explain information, but not both
    BufBuilder bb(FindCommon::kInitReplyBufferSize);
    bb.skip(sizeof(QueryResult::Value));

    // How many results have we obtained from the executor?
    int numResults = 0;

    BSONObj obj;
    PlanExecutor::ExecState state;

    // Get summary info about which plan the executor is using.
    {
        stdx::lock_guard<Client> lk(*opCtx->getClient());
        curOp.setPlanSummary_inlock(Explain::getPlanSummary(exec.get()));
    }

    while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
        // If we can't fit this result inside the current batch, then we stash it for later.
        if (!FindCommon::haveSpaceForNext(obj, numResults, bb.len())) {
            exec->enqueue(obj);
            break;
        }

        // Add result to output buffer.
        bb.appendBuf((void*)obj.objdata(), obj.objsize());

        // Count the result.
        ++numResults;

        if (FindCommon::enoughForFirstBatch(qr, numResults)) {
            LOG(5) << "Enough for first batch, wantMore=" << qr.wantMore()
                   << " ntoreturn=" << qr.getNToReturn().value_or(0)
                   << " numResults=" << numResults;
            break;
        }
    }

    // Caller expects exceptions thrown in certain cases.
    if (PlanExecutor::FAILURE == state || PlanExecutor::DEAD == state) {
        error() << "Plan executor error during find: " << PlanExecutor::statestr(state)
                << ", stats: " << redact(Explain::getWinningPlanStats(exec.get()));
        uassertStatusOKWithContext(WorkingSetCommon::getMemberObjectStatus(obj),
                                   "Executor error during OP_QUERY find");
        MONGO_UNREACHABLE;
    }

    // Before saving the cursor, ensure that whatever plan we established happened with the expected
    // collection version
    auto css = CollectionShardingState::get(opCtx, nss);
    css->checkShardVersionOrThrow(opCtx);

    // Fill out CurOp based on query results. If we have a cursorid, we will fill out CurOp with
    // this cursorid later.
    long long ccId = 0;

    if (shouldSaveCursor(opCtx, collection, state, exec.get())) {
        // We won't use the executor until it's getMore'd.
        exec->saveState();
        exec->detachFromOperationContext();

        // Allocate a new ClientCursor and register it with the cursor manager.
        ClientCursorPin pinnedCursor = collection->getCursorManager()->registerCursor(
            opCtx,
            {std::move(exec),
             nss,
             AuthorizationSession::get(opCtx->getClient())->getAuthenticatedUserNames(),
             opCtx->recoveryUnit()->getReadConcernLevel(),
             upconvertedQuery});
        ccId = pinnedCursor.getCursor()->cursorid();

        LOG(5) << "caching executor with cursorid " << ccId << " after returning " << numResults
               << " results";

        // TODO document
        if (qr.isExhaust()) {
            curOp.debug().exhaust = true;
        }

        pinnedCursor.getCursor()->setPos(numResults);

        // We assume that cursors created through a DBDirectClient are always used from their
        // original OperationContext, so we do not need to move time to and from the cursor.
        if (!opCtx->getClient()->isInDirectClient()) {
            // If the query had a time limit, remaining time is "rolled over" to the cursor (for
            // use by future getmore ops).
            pinnedCursor.getCursor()->setLeftoverMaxTimeMicros(opCtx->getRemainingMaxTimeMicros());
        }

        endQueryOp(opCtx, collection, *pinnedCursor.getCursor()->getExecutor(), numResults, ccId);
    } else {
        LOG(5) << "Not caching executor but returning " << numResults << " results.";
        endQueryOp(opCtx, collection, *exec, numResults, ccId);
    }

    // Fill out the output buffer's header.
    QueryResult::View queryResultView = bb.buf();
    queryResultView.setCursorId(ccId);
    queryResultView.setResultFlagsToOk();
    queryResultView.msgdata().setLen(bb.len());
    queryResultView.msgdata().setOperation(opReply);
    queryResultView.setStartingFrom(0);
    queryResultView.setNReturned(numResults);

    // Add the results from the query into the output buffer.
    result.setData(bb.release());

    // curOp.debug().exhaust is set above.
    return curOp.debug().exhaust ? nss.ns() : "";
}
void* rundle(void* socket){
    ServerSocket *client = (ServerSocket *) socket;
    std::string data;

    MessageStack messages;

    UserStack users;
    User *user;

    try {
        user = init_connection(client);
    }
    catch (SocketException& e) {
        printf("Error initial connection in function rundle()\n");
        return NULL;
    }

    try {
        users.join(user);
        user->send("Добро пожаловать, о ");
        user->send("\n---- // enter \"quit\" for exit\n\n");
        user->send(messages.viewLast());


        while (true) {
            data = *user->recive("> ");
            data = trimr(data);
            if ( data.compare("quit") == 0) {
                user->send("Bye! До скорых встреч");
                sleep(2);
                break;
            }
            if ( data.compare("help") == 0){
                user->send("\r==== Список пользователей ====\n");
            }
            if ( data.compare("who") == 0){
                user->send("\r==== Список пользователей ====\n");
                std::vector <User*> list = users.list();
                for (int i = list.size() - 1; i >= 0; --i){
                    user->send(list[i]->id);
                    user->send(": ");
                    user->send(list[i]->getName());
                    user->send("\n");
                }
                continue;
            }


            if ( data.length() == 0){
                continue;
            }

            Message *message = new Message(user->getName(), data);
            messages.append( message );
            users.sendMessage(message->get().c_str());
        }
    } catch (SocketException& e) {
        std::cout << "Exception was caught:" << e.description()
                << "\nExiting.\n";
    }

    users.disconnect(user);

    delete client;

    return NULL;
}