bool HttpMultiContentIO::addString(const QString &string, bool prefixBoundary) { if (!d_ptr->isDeviceOpen) { qWarning() << "HttpMultiContentIO::" << __FUNCTION__ << "called when device is not open yet"; return false; } if(d_ptr->bytesSent > 0) { qWarning() << "Already sent " << d_ptr->bytesSent << " bytes"; return false; } QBuffer *buff = new QBuffer(this); if (!buff->open (openMode())) { IODEVICE_ERROR("Could not open buffer in required mode"); } if((prefixBoundary) && (!d_ptr->boundaryString.isEmpty())) { buff->write("--"); if(buff->write(d_ptr->boundaryString.toUtf8()) == -1) { IODEVICE_ERROR("Write to buffer failed") } buff->write("\r\n"); } else if(prefixBoundary) {
void StationsPluginSimple::saveDiskCache() { QDomDocument doc; QFile file(diskCache()); QBuffer buffer; buffer.open(QIODevice::ReadWrite); buffer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); buffer.write("<cache>\n"); buffer.write(" <stations>\n"); foreach (Station *station, stations) { QString data = " <station id=\"%1\">\n" " <name>%2</name>\n" " <description>%3</description>\n" " <latitude>%4</latitude>\n" " <longitude>%5</longitude>\n" " </station>\n"; buffer.write(data.arg(station->id()) .arg(station->name()) .arg(station->description()) .arg(station->pos().x()) .arg(station->pos().y()) .toUtf8()); }
bool QInstaller::VerboseWriter::flush(VerboseWriterOutput *output) { stream.flush(); if (logFileName.isEmpty()) // binarycreator return true; if (!preFileBuffer.isOpen()) return true; //if the installer installed nothing - there is no target directory - where the logfile can be saved if (!QFileInfo(logFileName).absoluteDir().exists()) return true; QString logInfo; logInfo += QLatin1String("************************************* Invoked: "); logInfo += currentDateTimeAsString; logInfo += QLatin1String("\n"); QBuffer buffer; buffer.open(QIODevice::WriteOnly); buffer.write(logInfo.toLocal8Bit()); buffer.write(preFileBuffer.data()); buffer.close(); if (output->write(logFileName, QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text, buffer.data())) { preFileBuffer.close(); stream.setDevice(nullptr); return true; } return false; }
QByteArray FSTReader::writeMapping(const QVariantHash& mapping) { static const QStringList PREFERED_ORDER = QStringList() << NAME_FIELD << TYPE_FIELD << SCALE_FIELD << FILENAME_FIELD << TEXDIR_FIELD << JOINT_FIELD << FREE_JOINT_FIELD << BLENDSHAPE_FIELD << JOINT_INDEX_FIELD; QBuffer buffer; buffer.open(QIODevice::WriteOnly); for (auto key : PREFERED_ORDER) { auto it = mapping.find(key); if (it != mapping.constEnd()) { if (key == FREE_JOINT_FIELD) { // writeVariant does not handle strings added using insertMulti. for (auto multi : mapping.values(key)) { buffer.write(key.toUtf8()); buffer.write(" = "); buffer.write(multi.toByteArray()); buffer.write("\n"); } } else { writeVariant(buffer, it); } } } for (auto it = mapping.constBegin(); it != mapping.constEnd(); it++) { if (!PREFERED_ORDER.contains(it.key())) { writeVariant(buffer, it); } } return buffer.data(); }
void Response::redirect(const QUrl &url, quint16 status) { Q_D(Response); d->location = url; setStatus(status); if (url.isValid() && !d->body) { QBuffer *buf = new QBuffer; if (!buf->open(QIODevice::ReadWrite)) { qCCritical(CUTELYST_RESPONSE) << "Could not open QBuffer to write redirect!" << url << status; delete buf; return; } buf->write(QByteArrayLiteral("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0" "Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" " <head>\n" " <title>Moved</title>\n" " </head>\n" " <body>\n" " <p>This item has moved <a href=")); buf->write(url.toEncoded()); buf->write(QByteArrayLiteral(">here</a>.</p>\n" " </body>\n" "</html>\n")); d->body = buf; d->headers.setContentType(QStringLiteral("text/html; charset=utf-8")); } }
void tst_QRingBuffer::readPointerAtPositionWriteRead() { //create some data QBuffer inData; inData.open(QIODevice::ReadWrite); inData.putChar(0x42); inData.putChar(0x23); inData.write("Qt rocks!"); for (int i = 0; i < 5000; i++) inData.write(QString("Number %1").arg(i).toUtf8()); inData.reset(); QVERIFY(inData.size() > 0); //put the inData in the QRingBuffer QRingBuffer ringBuffer; qint64 remaining = inData.size(); while (remaining > 0) { // write in chunks of 50 bytes // this ensures there will be multiple QByteArrays inside the QRingBuffer // since QRingBuffer is then only using individual arrays of around 4000 bytes qint64 thisWrite = qMin(remaining, qint64(50)); char *pos = ringBuffer.reserve(thisWrite); inData.read(pos, thisWrite); remaining -= thisWrite; } // was data put into it? QVERIFY(ringBuffer.size() > 0); QCOMPARE(qint64(ringBuffer.size()), inData.size()); //read from the QRingBuffer in loop, put back into another QBuffer QBuffer outData; outData.open(QIODevice::ReadWrite); remaining = ringBuffer.size(); while (remaining > 0) { qint64 thisRead; // always try to read as much as possible const char *buf = ringBuffer.readPointerAtPosition(ringBuffer.size() - remaining, thisRead); outData.write(buf, thisRead); remaining -= thisRead; } outData.reset(); QVERIFY(outData.size() > 0); // was the data read from the QRingBuffer the same as the one written into it? QCOMPARE(outData.size(), inData.size()); QVERIFY(outData.buffer().startsWith(inData.buffer())); }
void CustomerInfoPanel::displayFiche(const QString & fichecontent, bool qtui, const QString & id) { Popup * popup = NULL; for(int i = m_popups.size() - 1; i >= 0; i --) { if(id == m_popups[i]->id()) { qDebug() << Q_FUNC_INFO << "fiche id already there" << i << id; popup = m_popups[i]; break; } } QBuffer * inputstream = new QBuffer(this); inputstream->open(QIODevice::ReadWrite); inputstream->write(fichecontent.toUtf8()); inputstream->close(); // Get Data and Popup the profile if ok if (popup == NULL) { popup = new Popup(m_autourl_allowed); m_popups.append(popup); popup->setId(id); connect(popup, SIGNAL(destroyed(QObject *)), this, SLOT(popupDestroyed(QObject *))); connect(popup, SIGNAL(wantsToBeShown(Popup *)), this, SLOT(showNewProfile(Popup *))); connect(popup, SIGNAL(actionFromPopup(const QString &, const QVariant &)), this, SLOT(actionFromPopup(const QString &, const QVariant &))); connect(popup, SIGNAL(newRemarkSubmitted(const QString &, const QString &)), b_engine, SLOT(sendNewRemark(const QString &, const QString &))); }
void sendDataToDev2(const QByteArray& data) { qint64 pos = mDevice2.pos(); mDevice2.write(data); mDevice2.seek(pos); // Return to qt event loop to allow it process asincronious signals QTest::qWait(1); }
bool QDataProtocol::GenerateCommonHeader( QBuffer& buffer ) { qint32 nUInt32Len = sizeof ( quint32 ); bool bRet = true; quint32 nIntValue = H2N< quint32 >( dataPackage.header.common.nDataLength ); buffer.write( ( const char* ) & nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.common.nReserved ); buffer.write( ( const char* ) & nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.common.eParcelType ); buffer.write( ( const char* ) & nIntValue, nUInt32Len ); return bRet; }
QVariant QJson::parse(const QByteArray& jsonString, bool* ok) { QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write(jsonString); buffer.seek(0); return parse (&buffer, ok); }
const QByteArray& QxtMailAttachment::rawData() const { if (qxt_d->content == 0) { qWarning("QxtMailAttachment::rawData(): Content not set!"); static QByteArray defaultRv; return defaultRv; } if (qobject_cast<QBuffer *>(qxt_d->content.data()) == 0) { // content isn't hold in a buffer but in another kind of QIODevice // (probably a QFile...). Read the data and cache it into a buffer static QByteArray empty; QIODevice* c = content(); if (!c->isOpen() && !c->open(QIODevice::ReadOnly)) { qWarning() << "QxtMailAttachment::rawData(): Cannot open content for reading"; return empty; } QBuffer* cache = new QBuffer(); cache->open(QIODevice::WriteOnly); char buf[1024]; while (!c->atEnd()) { cache->write(buf, c->read(buf, 1024)); } if (qxt_d->deleteContent && qxt_d->content) qxt_d->content->deleteLater(); qxt_d->content = cache; qxt_d->deleteContent = true; } return qobject_cast<QBuffer *>(qxt_d->content.data())->data(); }
void TestScanner::scanTokens() { QFETCH(QByteArray, input); QFETCH(bool, allowSpecialNumbers); QFETCH(bool, skipFirstToken); QFETCH(int, expectedResult); QFETCH(QVariant, expectedYylval); QFETCH(int, expectedLocationBeginLine); QFETCH(int, expectedLocationBeginColumn); QFETCH(int, expectedLocationEndLine); QFETCH(int, expectedLocationEndColumn); QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write(input); buffer.seek(0); JSonScanner scanner(&buffer); scanner.allowSpecialNumbers(allowSpecialNumbers); QVariant yylval; yy::position position(YY_NULL, 1, 0); yy::location location(position, position); int result = scanner.yylex(&yylval, &location); if (skipFirstToken) { result = scanner.yylex(&yylval, &location); } QCOMPARE(result, expectedResult); QCOMPARE(yylval, expectedYylval); QCOMPARE(location.begin.line, (uint)expectedLocationBeginLine); QCOMPARE(location.begin.column, (uint)expectedLocationBeginColumn); QCOMPARE(location.end.line, (uint)expectedLocationEndLine); QCOMPARE(location.end.column, (uint)expectedLocationEndColumn); }
void MT_CntVersitMyCardPlugin::importContact() { //import QBuffer input; input.open(QBuffer::ReadWrite); QByteArray inputVCard = "BEGIN:VCARD\r\nVERSION:2.1\r\nFN:John\r\nEND:VCARD\r\n"; input.write(inputVCard); input.seek(0); QVersitReader reader; reader.setDevice(&input); reader.startReading(); reader.waitForFinished(); // Use the resulting document(s)... QVersitContactImporter importer; QList<QVersitDocument> versitDocuments = reader.results(); importer.importDocuments(versitDocuments); QList<QContact> contacts = importer.contacts(); QVERIFY(1 == contacts.count()); // Check if MyCard detail is found QList<QContactDetail> details = contacts.first().details(MYCARD_DEFINTION_NAME); QVERIFY(details.count()==0); }
void flacStreamEncoderMetadataCallback( const FLAC__StreamEncoder *, const FLAC__StreamMetadata * _metadata, void * _client_data ) { QBuffer * b = static_cast<QBuffer *>( _client_data ); b->seek( 0 ); b->write( (const char *) _metadata, sizeof( *_metadata ) ); }
bool QDataProtocol::GenerateTableHeader( QBuffer& buffer ) { bool bRet = true; qint32 nUInt32Len = sizeof ( quint32 ); qint32 nUInt16Len = sizeof ( quint16 ); quint32 nIntValue = H2N< quint32 >( dataPackage.header.aux.headerTable.eType ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerTable.nColumnCount ); buffer.write( ( const char* ) &nIntValue, nUInt16Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerTable.nReserved ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerTable.nRowCount ); buffer.write( ( const char* ) &nIntValue, nUInt16Len ); return bRet; }
bool QDataProtocol::GenerateFileHeader( QBuffer& buffer ) { bool bRet = true; qint32 nUInt32Len = sizeof ( quint32 ); quint32 nIntValue = H2N< quint32 >( dataPackage.header.aux.headerFile.eType ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerFile.nContentLength ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerFile.nNameLength ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); nIntValue = H2N< quint32 >( dataPackage.header.aux.headerFile.nReserved ); buffer.write( ( const char* ) &nIntValue, nUInt32Len ); return bRet; }
void FSTReader::writeVariant(QBuffer& buffer, QVariantHash::const_iterator& it) { QByteArray key = it.key().toUtf8() + " = "; QVariantHash hashValue = it.value().toHash(); if (hashValue.isEmpty()) { buffer.write(key + it.value().toByteArray() + "\n"); return; } for (QVariantHash::const_iterator second = hashValue.constBegin(); second != hashValue.constEnd(); second++) { QByteArray extendedKey = key + second.key().toUtf8(); QVariantList listValue = second.value().toList(); if (listValue.isEmpty()) { buffer.write(extendedKey + " = " + second.value().toByteArray() + "\n"); continue; } buffer.write(extendedKey); for (QVariantList::const_iterator third = listValue.constBegin(); third != listValue.constEnd(); third++) { buffer.write(" = " + third->toByteArray()); } buffer.write("\n"); } }
int Connection::readBody(QTcpSocket *_sock, QBuffer& _body, int _length) { // DEBUG("need read body with len " << _length); if( !_length ) return 0; QByteArray data = _sock->read(_length); _body.write(data); _length -= data.size(); // DEBUG("readed body '" << data.data() << "', size " << data.size() << ", need read " << _length); return _length; }
void TestScanner::scanSpecialNumbers() { QFETCH(QByteArray, input); QFETCH(bool, isInfinity); QFETCH(bool, isNegative); QFETCH(bool, isNan); QFETCH(int, expectedLocationBeginLine); QFETCH(int, expectedLocationBeginColumn); QFETCH(int, expectedLocationEndLine); QFETCH(int, expectedLocationEndColumn); QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write(input); buffer.seek(0); JSonScanner scanner(&buffer); scanner.allowSpecialNumbers(true); QVariant yylval; yy::position position(YY_NULL, 1, 0); yy::location location(position, position); int result = scanner.yylex(&yylval, &location); QCOMPARE(result, TOKEN(NUMBER)); QVERIFY(yylval.type() == QVariant::Double); double doubleResult = yylval.toDouble(); #if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) QCOMPARE(bool(isinf(doubleResult)), isInfinity); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isinf(doubleResult)), isInfinity); #endif #endif QCOMPARE(doubleResult<0, isNegative); #if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) QCOMPARE(bool(isnan(doubleResult)), isNan); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isnan(doubleResult)), isNan); #endif #endif QCOMPARE(location.begin.line, (uint)expectedLocationBeginLine); QCOMPARE(location.begin.column, (uint)expectedLocationBeginColumn); QCOMPARE(location.end.line, (uint)expectedLocationEndLine); QCOMPARE(location.end.column, (uint)expectedLocationEndColumn); }
void completeExample() { // Create the input vCard //! [Complete example - create] QBuffer input; input.open(QBuffer::ReadWrite); QByteArray inputVCard = "BEGIN:VCARD\r\nVERSION:2.1\r\nFN:John Citizen\r\nN:Citizen;John;Q;;\r\nEND:VCARD\r\n"; input.write(inputVCard); input.seek(0); //! [Complete example - create] // Parse the input into QVersitDocuments //! [Complete example - read] // Note: we could also use the more convenient QVersitReader(QByteArray) constructor. QVersitReader reader; reader.setDevice(&input); reader.startReading(); // Remember to check the return value reader.waitForFinished(); QList<QVersitDocument> inputDocuments = reader.results(); //! [Complete example - read] // Convert the QVersitDocuments to QContacts //! [Complete example - import] QVersitContactImporter importer; if (!importer.importDocuments(inputDocuments)) return; QList<QContact> contacts = importer.contacts(); // Note that the QContacts are not saved yet. // Use QContactManager::saveContacts() for saving if necessary //! [Complete example - import] // Export the QContacts back to QVersitDocuments //! [Complete example - export] QVersitContactExporter exporter; if (!exporter.exportContacts(contacts, QVersitDocument::VCard30Type)) return; QList<QVersitDocument> outputDocuments = exporter.documents(); //! [Complete example - export] // Encode the QVersitDocument back to a vCard //! [Complete example - write] // Note: we could also use the more convenient QVersitWriter(QByteArray*) constructor. QBuffer output; output.open(QBuffer::ReadWrite); QVersitWriter writer; writer.setDevice(&output); writer.startWriting(outputDocuments); // Remember to check the return value writer.waitForFinished(); // output.buffer() now contains a vCard //! [Complete example - write] }
static void setBuffer_snippet() { //! [4] QByteArray byteArray("abc"); QBuffer buffer; buffer.setBuffer(&byteArray); buffer.open(QIODevice::WriteOnly); buffer.seek(3); buffer.write("def", 3); buffer.close(); // byteArray == "abcdef" //! [4] }
void FormDataFile::write(QBuffer& out) { QFile file(uri); Utilities::logData("Filename: " + fileName); if (!file.open(QIODevice::ReadOnly)) return; while (file.bytesAvailable() > 0) out.write(file.read(BUFFER_SIZE)); file.close(); }
void Load_Vcard::addNewContacts() { QFETCH(QString, vcard); QFETCH(QString, result); QList<QContact> contacts; QString res = QString("1"); QContactManager *cm = new QContactManager(); QContactSaveRequest *m_contactSaveRequest = new QContactSaveRequest(); m_contactSaveRequest->setManager(cm); //connect(&m_contactSaveRequest, SIGNAL(resultsAvailable()), this, // SLOT(contactsSaved())); QFile file(vcard); if (file.exists()) { QByteArray cardArr; if (file.open(QFile::ReadOnly)) { while (!file.atEnd()) { cardArr.append(file.readLine()); } } QBuffer input; input.open(QBuffer::ReadWrite); input.write(cardArr); input.seek(0); QVersitReader reader(cardArr); reader.startReading(); reader.waitForFinished(); QList<QVersitDocument> inputDocuments = reader.results(); QVersitContactImporter importer; if (importer.importDocuments(inputDocuments)) { contacts = importer.contacts(); m_contactSaveRequest->setContacts(contacts); m_contactSaveRequest->start(); m_contactSaveRequest->waitForFinished(); res = QString("0"); } input.close(); file.close(); } delete m_contactSaveRequest; delete cm; QCOMPARE(res, result); }
static void main_snippet() { //! [0] QBuffer buffer; char ch; buffer.open(QBuffer::ReadWrite); buffer.write("Qt rocks!"); buffer.seek(0); buffer.getChar(&ch); // ch == 'Q' buffer.getChar(&ch); // ch == 't' buffer.getChar(&ch); // ch == ' ' buffer.getChar(&ch); // ch == 'r' //! [0] }
void ShiftCoreTest::serialisationJsonTest() { TestDatabase db; auto rootA = db.addChild<Shift::Entity>(); buildTestData(rootA); QBuffer buffer; Shift::SaveBuilder builder; Shift::JSONSaver writer; writer.setAutoWhitespace(true); QBENCHMARK { buffer.setData(QByteArray()); buffer.open(QIODevice::ReadWrite); Eks::String data; auto block = writer.beginWriting(&data); builder.save(rootA, false, &writer); buffer.write(data.data(), data.size()); buffer.close(); } #define SAVE_OUTPUTx #ifdef SAVE_OUTPUT { QFileInfo path("./SerialisationTest.json"); qDebug() << path.absoluteFilePath(); QFile output(path.absoluteFilePath()); QCOMPARE(output.open(QFile::WriteOnly), true); output.write(buffer.data()); } #endif QFile expected(":/Serialisation/SerialisationTest.json"); QCOMPARE(expected.open(QFile::ReadOnly), true); QString savedOutput(buffer.data()); QString expectedOutput(expected.readAll()); QCOMPARE(checkStrings(savedOutput, expectedOutput), true); }
/** * \warning The caller has to delete the archive's underlying device */ KTar* ModelManager::archiveFromBuffer(const QByteArray& input) { // safely remove the const qualifier as the buffer is only opened read-only QBuffer buffer(const_cast<QByteArray*>(&input)); if (!buffer.open(QIODevice::ReadOnly)) return 0; QIODevice *uncompressed = KFilterDev::device(&buffer, "application/x-gzip", false); if (!uncompressed || !uncompressed->open(QIODevice::ReadOnly)) return 0; //seeking doesn't work properly in kfilterdevs, which trips up KTar. Instead, decompress //completely before passing it on to KTar QBuffer *uncompressedBuffer = new QBuffer; if (!uncompressedBuffer->open(QIODevice::ReadWrite)) return 0; uncompressedBuffer->write(uncompressed->readAll()); uncompressedBuffer->seek(0); delete uncompressed; return new KTar(uncompressedBuffer); }
/*! * Store contact */ CArrayFixFlat<TUid>* CNsmlContactsDataStoreExtensionPrivate::ImportContactsL( const TDesC8 &contactbufbase ) { _DBG_FILE("CNsmlContactsDataStoreExtensionPrivate::ImportContactsL: BEGIN"); DBG_DUMP((void*)contactbufbase.Ptr(), contactbufbase.Length(), _S8("CNsmlContactsDataStoreExtensionPrivate::ImportContactsL: To DB :")); TBool ret( ETrue ); CArrayFixFlat<TUid>* contactItems = new(ELeave) CArrayFixFlat<TUid>(4); QBuffer contactsbuf; contactsbuf.open(QBuffer::ReadWrite); QByteArray bytearray((char*)contactbufbase.Ptr()); contactsbuf.write(bytearray); contactsbuf.seek(0); mReader->setDevice(&contactsbuf); if (mReader->startReading() && mReader->waitForFinished()) { DBG_ARGS(_S("CNsmlContactsDataStoreExtensionPrivate::Buffer Count: %d"), mReader->results().count() ); QList<QContact> contacts; if ( mImporter->importDocuments( mReader->results() ) ) { contacts = mImporter->contacts(); QMap<int, QContactManager::Error> errorMap; ret = mContactManager->saveContacts( &contacts, &errorMap ); DBG_ARGS(_S("CNsmlContactsDataStoreExtensionPrivate::Import Status: %d"), ret ); } if( ret ) { foreach (QContact contact, contacts ) { TUint contactid = contact.id().localId(); DBG_ARGS(_S("CNsmlContactsDataStoreExtensionPrivate::Contact ID: %d"), contactid ); contactItems->AppendL( TUid::Uid( contactid ) ); } }
void tst_QIODevice::getch() { #ifdef QT3_SUPPORT QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write("\xff\x7f\x80\x00", 4); buffer.reset(); QCOMPARE(buffer.getch(), 0xff); QCOMPARE(buffer.getch(), 0x7f); QCOMPARE(buffer.getch(), 0x80); QCOMPARE(buffer.getch(), 0x00); buffer.ungetch(0x00); buffer.ungetch(0x80); buffer.ungetch(0x7f); buffer.ungetch(0xff); QCOMPARE(buffer.getch(), 0xff); QCOMPARE(buffer.getch(), 0x7f); QCOMPARE(buffer.getch(), 0x80); QCOMPARE(buffer.getch(), 0x00); #endif }
//-------------------------------------------------------------------- void tst_QIODevice::unget() { #if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST) QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll); #endif QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write("ZXCV"); buffer.seek(0); QCOMPARE(buffer.read(4), QByteArray("ZXCV")); QCOMPARE(buffer.pos(), qint64(4)); buffer.ungetChar('a'); buffer.ungetChar('b'); buffer.ungetChar('c'); buffer.ungetChar('d'); QCOMPARE(buffer.pos(), qint64(0)); char buf[6]; QCOMPARE(buffer.readLine(buf, 5), qint64(4)); QCOMPARE(buffer.pos(), qint64(4)); QCOMPARE(static_cast<const char*>(buf), "dcba"); buffer.ungetChar('a'); buffer.ungetChar('b'); buffer.ungetChar('c'); buffer.ungetChar('d'); QCOMPARE(buffer.pos(), qint64(0)); for (int i = 0; i < 5; ++i) { buf[0] = '@'; buf[1] = '@'; QTest::ignoreMessage(QtWarningMsg, "QIODevice::readLine: Called with maxSize < 2"); QCOMPARE(buffer.readLine(buf, 1), qint64(-1)); QCOMPARE(buffer.readLine(buf, 2), qint64(i < 4 ? 1 : -1)); switch (i) { case 0: QCOMPARE(buf[0], 'd'); break; case 1: QCOMPARE(buf[0], 'c'); break; case 2: QCOMPARE(buf[0], 'b'); break; case 3: QCOMPARE(buf[0], 'a'); break; case 4: QCOMPARE(buf[0], '\0'); break; } QCOMPARE(buf[1], i < 4 ? '\0' : '@'); } buffer.ungetChar('\n'); QCOMPARE(buffer.readLine(), QByteArray("\n")); buffer.seek(1); buffer.readLine(buf, 3); QCOMPARE(static_cast<const char*>(buf), "XC"); buffer.seek(4); buffer.ungetChar('Q'); QCOMPARE(buffer.readLine(buf, 3), qint64(1)); for (int i = 0; i < 2; ++i) { QTcpSocket socket; QIODevice *dev; QByteArray result; const char *lineResult; if (i == 0) { dev = &buffer; result = QByteArray("ZXCV"); lineResult = "ZXCV"; } else { socket.connectToHost(QtNetworkSettings::serverName(), 80); socket.write("GET / HTTP/1.0\r\n\r\n"); QVERIFY(socket.waitForReadyRead()); dev = &socket; result = QByteArray("HTTP"); lineResult = "Date"; } char ch, ch2; dev->seek(0); dev->getChar(&ch); dev->ungetChar(ch); QCOMPARE(dev->peek(4), result); dev->getChar(&ch); dev->getChar(&ch2); dev->ungetChar(ch2); dev->ungetChar(ch); QCOMPARE(dev->read(1), result.left(1)); QCOMPARE(dev->read(3), result.right(3)); if (i == 0) dev->seek(0); else dev->readLine(); dev->getChar(&ch); dev->ungetChar(ch); dev->readLine(buf, 5); QCOMPARE(static_cast<const char*>(buf), lineResult); if (i == 1) socket.close(); } }
void Server::riceviMessaggio() { QTcpSocket* socket; QBuffer* buffer; QByteArray line; socket = (QTcpSocket*)(sender()); buffer = buffers.value(socket); qint64 bytes = buffer->write(socket->readAll()); //Per la ricezione del messaggio. buffer->seek(buffer->pos() - bytes); while (buffer->canReadLine()) //Leggo fino a quando sono presenti linee di testo. { line = buffer->readLine(); if(line.startsWith('#')) //Richiesta di autenticazione. { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("./users.sqldb"); if (!db.open()) { socket->write("#false"); } QSqlQuery s; QString nome; QString password; QList<QByteArray> nomepassword; nomepassword = line.split('/'); nome = nomepassword[1]; password = nomepassword[2]; password = password.remove("\n"); s.prepare("SELECT Username FROM Utenti WHERE Username = '******' AND Password = '******'"); s.exec(); s.next(); QString username = s.value(0).toString(); if(username != "") { socket->write("#true\n"); } else { socket->write("#false\n"); } db.close(); } else if(line.startsWith('!')) //Richiesta di iscrizione. { QString nome; QString password; QList<QByteArray> nomepassword = line.split('/'); db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("./users.sqldb"); db.open(); QSqlQuery s; nome = nomepassword[1]; password = nomepassword[2]; password = password.remove("\n"); s.prepare("INSERT INTO Utenti VALUES ('" + nome + "', '" + password + "')"); s.exec(); db.close(); } else foreach (QTcpSocket* connection, connections) { connection->write(line); //Invio il testo ricevuto a un'altra connessione. } }