bool ResponseCollector::matchExpected(DataBuffer& data) { //make a save point so we can revert if need be ReadBufferSavePoint savepoint(&data); size_t startBytesRemaining = 0; //get a lock on the response mutex mutex_lock_guard lock(m_responseMutex); //need to loop over all of the bytes to check for responses while(data.moreToRead()) { //log the bytes remaining in the data before we attempt to match startBytesRemaining = data.bytesRemaining(); //look through all the expected responses for(auto itr = m_expectedResponses.begin(); itr < m_expectedResponses.end(); itr++) { //don't try to match bytes that were in the buffer before the command was sent if(data.readPosition() < itr->minBytePosition) { continue; } //if we found a match if(itr->pattern->match(data)) { //match functions move the data pointer on success (even if not fully matched) //need to make sure we don't roll back to our previous savepoint. savepoint.commit(); if(itr->pattern->fullyMatched()) { //unregister the response m_expectedResponses.erase(itr); return true; } } //if any match function moved the data pointer, we don't want to move it back here if(startBytesRemaining != data.bytesRemaining()) { savepoint.commit(); } } //if we can move to the next byte and the byte position hasn't been moved elsewhere (internally by a match function). if(data.moreToRead() && startBytesRemaining == data.bytesRemaining()) { //move to the next byte and check for the response again data.read_uint8(); } } return false; }
PRUint16 UpdateHelper::DoDatabaseWork(mozIStorageConnection* aConnection) { NS_PRECONDITION(aConnection, "Passed a null connection!"); nsresult rv; NS_ASSERTION(!mKey.IsUnset() && !mKey.IsNull(), "Badness!"); nsCOMPtr<mozIStorageStatement> stmt = mTransaction->AddStatement(false, true, mAutoIncrement); NS_ENSURE_TRUE(stmt, nsIIDBDatabaseException::UNKNOWN_ERR); mozStorageStatementScoper scoper(stmt); Savepoint savepoint(mTransaction); NS_NAMED_LITERAL_CSTRING(keyValue, "key_value"); rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("osid"), mOSID); NS_ENSURE_SUCCESS(rv, nsIIDBDatabaseException::UNKNOWN_ERR); if (mKey.IsInt()) { rv = stmt->BindInt64ByName(keyValue, mKey.IntValue()); } else if (mKey.IsString()) { rv = stmt->BindStringByName(keyValue, mKey.StringValue()); } else { NS_NOTREACHED("Unknown key type!"); } NS_ENSURE_SUCCESS(rv, nsIIDBDatabaseException::UNKNOWN_ERR); rv = stmt->BindStringByName(NS_LITERAL_CSTRING("data"), mValue); NS_ENSURE_SUCCESS(rv, nsIIDBDatabaseException::UNKNOWN_ERR); if (NS_FAILED(stmt->Execute())) { return nsIIDBDatabaseException::CONSTRAINT_ERR; } // Update our indexes if needed. if (!mIndexUpdateInfo.IsEmpty()) { PRInt64 objectDataId = mAutoIncrement ? mKey.IntValue() : LL_MININT; rv = IDBObjectStore::UpdateIndexes(mTransaction, mOSID, mKey, mAutoIncrement, true, objectDataId, mIndexUpdateInfo); if (rv == NS_ERROR_STORAGE_CONSTRAINT) { return nsIIDBDatabaseException::CONSTRAINT_ERR; } NS_ENSURE_SUCCESS(rv, nsIIDBDatabaseException::UNKNOWN_ERR); } rv = savepoint.Release(); return NS_SUCCEEDED(rv) ? OK : nsIIDBDatabaseException::UNKNOWN_ERR; }
int main() { savepoint("=========================="); char buf_bat[200] = {0}; char buf_back[200] = {0}; char buf_net[200] = {0}; char buf_audio[200] = {0}; char buf_date[200] = {0}; char buf_ws[300] = {0}; savepoint("allocation"); get_workspace(buf_ws); savepoint("workspace"); get_battery(buf_bat); savepoint("battery"); get_audio(buf_audio); savepoint("audio"); get_date(buf_date); savepoint("date"); if (get_network(buf_net) == 1) { get_backlight(buf_back, COLOR_BG_NET); savepoint("backlight"); printf("%%{l}%s %%{r}%s %s %s %s %s%%{F%s}%%{B%s}\n", buf_ws, buf_audio, buf_net, buf_back, buf_bat, buf_date, COLOR_BG, COLOR_BG); } else { get_backlight(buf_back, COLOR_BG_AUDIO); savepoint("backlight"); printf("%%{F%s}%%{B%s}%%{l}%s%%{F%s}%%{B%s} %%{r}%s %s %s %s%%{F%s}%%{B%s}\n",COLOR_BG, COLOR_BG, buf_ws, COLOR_BG, COLOR_BG, buf_audio, buf_back, buf_bat, buf_date, COLOR_BG, COLOR_BG); } savepoint("print"); savepoint("=========================="); return 0; }
void WirelessParser::parse(DataBuffer& data, WirelessTypes::Frequency freq) { ParsePacketResult parseResult; //holds the result of verifying whether it was a valid ASPP packet or not WirelessPacket packet; size_t bytesRemaining; //holds how many bytes we have remaining, helps determine if the buffer has been moved by an external function //make a save point so we can revert if need be ReadBufferSavePoint savepoint(&data); std::size_t lastReadPosition; //while there is more data to be read in the DataBuffer while(data.moreToRead()) { lastReadPosition = data.readPosition(); //read the next byte (doesn't move data's read position) uint8 currentByte = data.peekByte(); //skipByte is set to false when we don't want to skip to the next byte after we are done looking at the current byte bool moveToNextByte = true; //notEnoughData is true when the bytes could be a valid packet, but there isn't enough bytes to be sure bool notEnoughData = false; //if this is any ASPP Start of Packet byte if(currentByte == WirelessPacket::ASPP_V1_START_OF_PACKET_BYTE || currentByte == WirelessPacket::ASPP_V2_START_OF_PACKET_BYTE) { //check if the packet is a valid ASPP packet, starting at this byte parseResult = parseAsPacket(data, packet, freq); //check the result of the parseAsPacket command switch(parseResult) { //good packet, process it and then look for the next case parsePacketResult_completePacket: processPacket(packet, lastReadPosition); savepoint.commit(); continue; //packet has been processed, move to the next byte after the packet case parsePacketResult_duplicate: savepoint.commit(); continue; //packet is a duplicate, but byte position has been moved. Move to the next byte after the packet //somethings incorrect in the packet, move passed the AA and start looking for the next packet case parsePacketResult_invalidPacket: case parsePacketResult_badChecksum: savepoint.commit(); break; //ran out of data, return and wait for more case parsePacketResult_notEnoughData: moveToNextByte = false; notEnoughData = true; break; default: assert(false); //unhandled verifyResult, need to add a case for it } } //data is not a packet at this point bytesRemaining = data.bytesRemaining(); //check if the bytes we currently have match an expected response // This isn't perfect (could possibly use part of a partial ASPP packet as a cmd response), // but unfortunately its the best we can do with single byte responses being part of our protocol if(findMatchingResponse(data)) { //the bytes have already moved, don't move to the next byte in the next iteration savepoint.commit(); moveToNextByte = false; } else { //failed to match //if we didn't have enough data for a full packet, and it didn't match any expected responses if(notEnoughData) { //look for packets after the current byte. // Even though this looks like it could be the start of an ASPP packet, // if we find any full ASPP packets inside of the these bytes, we need // to pick them up and move on. if(!findPacketInBytes(data, freq)) { //if the read position in the bytes has been moved external to this function if(data.bytesRemaining() != bytesRemaining) { //read position has moved somewhere else, so bytes have been committed. Commit in our local savepoint as well. savepoint.commit(); } //we didn't find a packet within this, so return from this function as we need to wait for more data return; } else { savepoint.commit(); } } } //if we need to move to the next byte if (moveToNextByte) { //if the read position in the bytes has been moved external to this function if(data.bytesRemaining() != bytesRemaining) { //read position has moved somewhere else, so bytes have been committed. Commit in our local savepoint as well. savepoint.commit(); } else { //move to the next byte data.read_uint8(); } } } }
bool CSVToolWindow::importStart() { QString mapname = atlasWindow()->map(); CSVAtlas *atlas = _atlasWindow->getAtlas(); if (mapname.isEmpty()) { QStringList mList = atlas->mapList(); if(mList.isEmpty()) { _msghandler->message(QtWarningMsg, tr("No Maps Loaded"), tr("<p>There are no maps loaded to select from. " "Either load an atlas that contains maps or " "create a new one before continuing.")); return false; } mList.sort(); bool valid; mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"), mList, 0, false, &valid); if (!valid) return false; } CSVMap map = atlas->map(mapname); map.simplify(); QList<CSVMapField> fields = map.fields(); if (map.name() != mapname || fields.isEmpty()) { _msghandler->message(QtWarningMsg, tr("Invalid Map"), tr("<p>The selected map does not appear to be valid.")); return false; } CSVMap::Action action = map.action(); if (action != CSVMap::Insert) { _msghandler->message(QtWarningMsg, tr("Action not implemented"), tr("<p>The action %1 for this map is not supported.") .arg(CSVMap::actionToName(action))); return false; } if (!_data || _data->rows() < 1) { _msghandler->message(QtWarningMsg, tr("No data"), tr("<p>There are no data to process. " "Load a CSV file before continuing.")); return false; } int total = _data->rows(); int current = 0, error = 0, ignored = 0; if (! _log) _log = new LogWindow(this); if(usetransaction) QSqlQuery begin("BEGIN;"); QString errMsg; if(!map.sqlPre().trimmed().isEmpty()) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;"); QSqlQuery pre; if(!pre.exec(map.sqlPre())) { errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(map.sqlPreContinueOnError()) { _log->_log->append(tr("\n\nContinuing with rest of import\n\n")); if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;"); if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;"); } else { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtWarningMsg, tr("Error"), tr("<p>There was an error running the Pre SQL " "query. " "Aborting transaction." "\n\n----------------------\n%1").arg(errMsg)); return false; } } } QString progresstext(tr("Importing %1: %2 rows out of %3")); int expected = total; QProgressDialog *progress = new QProgressDialog(progresstext .arg(map.name()).arg(0).arg(expected), tr("Cancel"), 0, expected, this); progress->setWindowModality(Qt::WindowModal); bool userCanceled = false; QString query; QString front; QString back; QString value; QString label; QVariant var; QStringList errorList; for(current = 0; current < total; ++current) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;"); if(action == CSVMap::Insert) { query = QString("INSERT INTO %1 ").arg(map.table()); front = "("; back = " VALUES("; QList<CSVMapField> fields = map.fields(); QMap<QString,QVariant> values; for (int i = 0; i < fields.size(); i++) { switch(fields.at(i).action()) { case CSVMapField::Action_UseColumn: { value = _data->value(current, fields.at(i).column()-1); if(value.isNull()) { switch (fields.at(i).ifNullAction()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::UseAlternateColumn: { value = _data->value(current, fields.at(i).columnAlt()-1); if(value.isNull()) { switch (fields.at(i).ifNullActionAlt()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } case CSVMapField::Action_UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::Action_UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::Action_UseNull: { var = QVariant(QString::null); break; } default: continue; } label = ":" + fields.at(i).name(); if(!values.empty()) { front += ", "; back += ", "; } values.insert(label, var); front += fields.at(i).name(); back += label; } if(values.empty()) { ignored++; errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1); errorList.append(errMsg); continue; } front += ") "; back += ")"; query += front + back; QSqlQuery qry; qry.prepare(query); QMap<QString,QVariant>::iterator vit; for(vit = values.begin(); vit != values.end(); ++vit) qry.bindValue(vit.key(), vit.value()); if(!qry.exec()) { if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;"); error++; errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text()); errorList.append(errMsg); } } if (progress->wasCanceled()) { userCanceled = true; break; } if(! (current % 1000)) { progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected)); progress->setValue(current); } } progress->setValue(total); if (error || ignored || userCanceled) { _log->_log->append(tr("Map: %1\n" "Table: %2\n" "Method: %3\n\n" "Total Records: %4\n" "# Processed: %5\n" "# Ignored: %6\n" "# Errors: %7\n\n") .arg(map.name()).arg(map.table()) .arg(CSVMap::actionToName(map.action())) .arg(total).arg(current).arg(ignored).arg(error)); _log->_log->append(errMsg); _log->_log->append(errorList.join("\n")); _log->show(); _log->raise(); if (_msghandler && // log messages there's a non-interactive message handler qobject_cast<XAbstractMessageHandler*>(_msghandler) && ! qobject_cast<InteractiveMessageHandler*>(_msghandler)) _msghandler->message(error ? QtCriticalMsg : QtWarningMsg, tr("Import Processing Status"), _log->_log->toPlainText()); } if (! userCanceled && ! map.sqlPost().trimmed().isEmpty()) { QSqlQuery post; if(!post.exec(map.sqlPost())) { errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtCriticalMsg, tr("Error"), tr("<p>There was an error running the post sql " "query and changes were rolled back. " "\n\n----------------------\n%1").arg(errMsg)); return false; } } if (userCanceled) { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back.")); return false; } if(usetransaction) QSqlQuery commit("COMMIT"); if (! error) { _msghandler->message(QtDebugMsg, tr("Import Complete"), tr("The import of %1 completed successfully.") .arg(_currentDir)); return true; } return false; }
void CfgCategory::begin() { savepoint(true); }