bool UdpDecorator::execute(Request &req, QIODevice &io) { form(req); io.readAll(); io.write(req.getBody()); QByteArray rxData; int cnt = 0; while(1) { int wait = 15; if(req.getWaitTime()!=0) wait = req.getWaitTime(); int length=0; for(int i=0; i<wait; i++) { QThread::currentThread()->msleep(1); rxData+=io.readAll(); if(rxData.count()) { if(length==rxData.count()) break; length = rxData.count(); } } if(rxData.count()) { req.updateRdData(rxData); req.setAnswerData(rxData); if(checkAnAnswer(req)) { getAnAnswer(req); return true; } } else cnt++; if(cnt>=20) { req.setAnswerData(QByteArray()); break; } } return false; }
QPixmap CustomizationService::getServerLogo(const Account& account) { QPixmap logo = QPixmap(":/images/seafile-24.png"); if (account.serverInfo.customLogo.isEmpty()) { return logo; } QUrl url = account.getAbsoluteUrl(account.serverInfo.customLogo); QIODevice* buf = disk_cache_->data(url); if (buf) { logo.loadFromData(buf->readAll()); buf->close(); delete buf; } if (!reqs_.contains(url.toString())) { FetchCustomLogoRequest* req = new FetchCustomLogoRequest(url); connect(req, SIGNAL(success(const QUrl&)), this, SLOT(onServerLogoFetched(const QUrl&))); connect(req, SIGNAL(failed(const ApiError&)), this, SLOT(onServerLogoFetchFailed(const ApiError&))); req->send(); reqs_[url.toString()] = req; }
void GeoEngine::saveCachedTiles(QProgressBar* progressbar) { QNetworkDiskCache* cache = (QNetworkDiskCache*)(manager->cache()); QDirIterator it1(cache->cacheDirectory()+QString("http/")); int nbFiles = 0; while(it1.hasNext()) { nbFiles++; it1.next(); } QDirIterator it(cache->cacheDirectory()+QString("http/")); progressbar->setMaximum(nbFiles); progressbar->setMinimum(0); progressbar->show(); progressbar->raise(); int numFile=0; while(it.hasNext()) { progressbar->setValue(numFile++); it.next(); if(it.fileInfo().isFile()) { QNetworkCacheMetaData metaData = cache->fileMetaData(it.filePath()); QIODevice* data = cache->data(metaData.url()); if(data) { saveTileToDisk(metaData.url(),data->readAll()); delete data; } } } progressbar->hide(); }
void Interceptor::handleReadChannelFinished () { QIODevice *source = static_cast<QIODevice*> (sender ()); Data_ [source] += source->readAll (); Data_.remove (source); }
QByteArray QIODeviceProto::readAll() { QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject()); if (item) return item->readAll(); return QByteArray(); }
bool LoadFromJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion) { QByteArray json = f.readAll(); if(json.isEmpty()) { qCritical() << "Read invalid empty JSON data from file " << f.errorString(); return false; } QJsonDocument doc = QJsonDocument::fromJson(json); if(doc.isEmpty() || doc.isNull()) { qCritical() << "Failed to convert file to JSON document"; return false; } data = doc.toVariant().toMap(); if(data.isEmpty() || !data.contains(magicIdentifier)) { qCritical() << "Converted config data is invalid or unrecognised"; return false; } if(data[magicIdentifier].toUInt() != magicVersion) { qCritical() << "Converted config data is not the right version"; return false; } return true; }
void QxtRPCServicePrivate::clientData(quint64 id) { // Get the device from the connection manager. QIODevice* dev = manager->client(id); // Cache a reference to the buffer. QByteArray& buf = buffers[id]; // Read all available data on the device. buf.append(dev->readAll()); while(serializer->canDeserialize(buf)) { // Extract one deserialized signal from the buffer. QxtAbstractSignalSerializer::DeserializedData data = serializer->deserialize(buf); // Check to see if it's a blank command. if(serializer->isNoOp(data)) continue; // Check for protocol errors. if(serializer->isProtocolError(data)) { qWarning() << "QxtRPCService: Invalid data received; disconnecting"; qxt_p().disconnectClient(id); return; } // Pad the arguments to 8, because that's what dispatchFromClient() expects. while(data.second.count() < 8) data.second << QVariant(); // And finally, invoke the dispatcher. dispatchFromClient(id, data.first, data.second[0], data.second[1], data.second[2], data.second[3], data.second[4], data.second[5], data.second[6], data.second[7]); } }
void BenchmarkCodeCompletion::initTestCase() { AutoTestShell::init(); TestCore* core = new TestCore(); core->initialize(KDevelop::Core::NoUi); DUChain::self()->disablePersistentStorage(); // make sure we have a valid duchain for the global file DUChainReadLocker lock(DUChain::lock()); if ( !DUChain::self()->chainForDocument(internalFunctionFile()) ) { kDebug() << "no internal function file found in DUChain, loading it manually"; QString fileName = internalFunctionFile().str(); QString mimeType = KMimeType::findByPath(fileName, 0, false)->name (); QIODevice* file = KFilterDev::deviceForFile (fileName, mimeType, false); if ( !file->open(QIODevice::ReadOnly) ) { kDebug() << "Could not open file" << fileName; return; } lock.unlock(); parseAdditionalFile(internalFunctionFile(), file->readAll()); delete file; DUChain::self()->storeToDisk(); } }
void recursive_print( const KArchiveDirectory * dir, const QString & path ) { QStringList l = dir->entries(); l.sort(); QStringList::ConstIterator it = l.constBegin(); for( ; it != l.constEnd(); ++it ) { const KArchiveEntry* entry = dir->entry( (*it) ); printf("mode=%07o %s %s %s %s%s %lld isdir=%d\n", entry->permissions(), entry->datetime().toString("yyyy-MM-dd hh:mm:ss").toLatin1().constData(), entry->user().toLatin1().constData(), entry->group().toLatin1().constData(), path.toLatin1().constData(), (*it).toLatin1().constData(), entry->isFile() ? static_cast<const KArchiveFile *>(entry)->size() : 0, entry->isDirectory()); if (!entry->symLinkTarget().isEmpty()) { printf(" (symlink to %s)\n",qPrintable(entry->symLinkTarget())); } if (entry->isDirectory()) recursive_print( (KArchiveDirectory *)entry, path+(*it)+'/' ); if (entry->isFile()) { const KArchiveFile* f = static_cast<const KArchiveFile*>( entry ); QByteArray arr( f->data() ); qDebug() << "data" << arr; QIODevice *dev = f->createDevice(); QByteArray contents = dev->readAll(); qDebug() << "contents" << contents; delete dev; } } }
bool RkCommand::waitAnAnswer(Request &req, QIODevice &io) { if(io.isOpen()){ QByteArray answer; if(io.waitForReadyRead(100)){ int cnt=0; answer+=io.readAll(); while(io.waitForReadyRead(10)) { answer+=io.readAll(); cnt++;if(cnt>=maxCnt) break; } } req.updateRdData(answer); if(answer.count()) {return true;} } return false; }
void Worker::peerReadyReadHandler(void) { QIODevice* peer = qobject_cast<QIODevice*>(this->sender()); Q_ASSERT(peer != 0); if (this->m_state == Worker::ErrorState) { // Peer has not disconnected (though it should have) - closing the connection Q_EMIT this->error(Worker::UnknownError); peer->close(); return; } QByteArray buf; buf = peer->readAll(); this->m_buf.append(buf); bool cont; do { cont = false; switch(this->m_state) { case Worker::ConnectedState: cont = this->readGreeting(); break; case Worker::GreetingReceivedState: this->parseGreeting(); break; case Worker::AwaitingAuthenticationState: this->authenticate(); break; case Worker::AwaitingRequestState: this->parseRequest(); break; case Worker::RequestReceivedState: this->m_state = Worker::FatalErrorState; break; case Worker::ConnectionProxiedState: Q_ASSERT(this->m_target != 0); this->m_target->write(this->m_buf); this->m_target->flush(); this->m_buf.clear(); break; case Worker::ErrorState: case Worker::FatalErrorState: Q_ASSERT(false); break; } } while (cont); if (this->m_state == Worker::FatalErrorState) { peer->close(); } }
bool RkCommand::waitAnAnswer(Request &req, QIODevice &io) { static const int maxCnt = 500; // ограничение ожидания ответа при длительном входящем потоке данных if(io.isOpen()) { QByteArray answer; if(io.waitForReadyRead(100)) { int cnt=0; answer+=io.readAll(); while(io.waitForReadyRead(10)) { answer+=io.readAll(); cnt++; if(cnt>=maxCnt) break; } } req.updateRdData(answer); if(answer.count()) return true; } return false; }
/*! * Returns the data, modified by setData if modified, for the file named \a filePath. * \sa file(), fileData(), modifiedFile() */ QByteArray Archive::modifiedFileData(const QString &filePath) { QIODevice *io = modifiedFile(filePath); if(io == NULL || !io->open(QIODevice::ReadOnly)) { qWarning() << "Archive::modifiedFileData error"; return QByteArray(); } QByteArray data = io->readAll(); io->close(); return data; }
void MockHttpNetworkReplyPrivate::receive() { if (!device) { Q_Q(MockHttpNetworkReply); emit q->error(QNetworkReply::ConnectionRefusedError); emit q->finished(); return; } buffer = device->readAll(); parse(); }
/*! Read the unformatted contents of the file associated with a QContent into \a data. If \a data is not empty the contents will be overridden. Returns true if data could be read from the file and false otherwise. */ bool QContent::load(QByteArray &data) const { QIODevice *dev = open(); if (!dev) return false; if (dev->size() > 0) data = dev->readAll(); dev->close(); delete dev; return true; }
QByteArray Manifest::decryptFile( const QString &filename, const QByteArray &fileData ) { #ifdef QCA2 ManifestEntry *entry = entryByName( filename ); if ( ! QCA::isSupported( "sha1" ) ) { KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a hashing plugin could not be located") ); // in the hope that it wasn't really encrypted... return QByteArray( fileData ); } if ( ! QCA::isSupported( "pbkdf2(sha1)") ) { KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a key derivation plugin could not be located") ); // in the hope that it wasn't really encrypted... return QByteArray( fileData ); } if ( ! QCA::isSupported( "blowfish-cfb") ) { KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a cipher plugin could not be located") ); // in the hope that it wasn't really encrypted... return QByteArray( fileData ); } QByteArray decryptedData; checkPassword( entry, fileData, &decryptedData ); if (! m_haveGoodPassword ) { return QByteArray(); } QIODevice *decompresserDevice = new KCompressionDevice( new QBuffer( &decryptedData, 0 ), true, KCompressionDevice::GZip); if( !decompresserDevice ) { qCDebug(OkularOooDebug) << "Couldn't create decompressor"; // hopefully it isn't compressed then! return QByteArray( fileData ); } static_cast<KFilterDev*>( decompresserDevice )->setSkipHeaders( ); decompresserDevice->open( QIODevice::ReadOnly ); return decompresserDevice->readAll(); #else // TODO: This should have a proper parent KMessageBox::error( 0, i18n("This document is encrypted, but Okular was compiled without crypto support. This document will probably not open.") ); // this is equivalent to what happened before all this Manifest stuff :-) return QByteArray( fileData ); #endif }
bool readJSONFile(QIODevice& device, QSettings::SettingsMap& map) { QJsonParseError jsonParseError; auto bytesRead = device.readAll(); auto document = QJsonDocument::fromJson(bytesRead, &jsonParseError); if (jsonParseError.error != QJsonParseError::NoError) { qCDebug(shared) << "Error parsing QSettings file:" << jsonParseError.errorString(); return false; } map = jsonDocumentToVariantMap(document); return true; }
QString KSVGLoader::loadXML(::KURL url) { QString tmpFile; if(KIO::NetAccess::download(url, tmpFile, 0)) { QIODevice *dev = KFilterDev::deviceForFile(tmpFile, "application/x-gzip", true); QByteArray contents; if(dev->open(IO_ReadOnly)) contents = dev->readAll(); delete dev; KIO::NetAccess::removeTempFile(tmpFile); return QString(contents); } return QString::null; }
void Model::parseContainer() { if (!m_container.isNull()) { QBuffer model(&m_container); model.open(QIODevice::ReadOnly); QIODevice *filter = KFilterDev::device(&model, "application/x-gzip", false /* will be deleted when unwinding stack */); filter->open(QIODevice::ReadOnly); QByteArray uncompressed = filter->readAll(); delete filter; //KTar doesn't work with KFilterDev for some reason... QBuffer uncompressedModel(&uncompressed); uncompressedModel.open(QIODevice::ReadOnly); KTar archive(&uncompressedModel); parseContainer(archive, m_modelCreationDate, m_modelName, m_type); } m_containerParsed = true; }
void SocketApi::slotNewConnection() { QIODevice* socket = _localServer.nextPendingConnection(); if( ! socket ) { return; } DEBUG << "New connection" << socket; connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(onLostConnection())); Q_ASSERT(socket->readAll().isEmpty()); _listeners.append(socket); foreach( Folder *f, FolderMan::instance()->map() ) { QString message = buildRegisterPathMessage(f->path()); sendMessage(socket, message); }
static void process(QString url, const QByteArray &metadata, QNetworkAccessManager &nam) { url = url.simplified(); if (url.isEmpty()) return; if (url.startsWith("file://")) url = url.mid(7); QIODevice *device = NULL; if (QFileInfo(url).exists()) { device = new QFile(url); device->open(QIODevice::ReadOnly); } else { QNetworkReply *reply = nam.get(QNetworkRequest(url)); while (!reply->isFinished()) QCoreApplication::processEvents(); if (reply->error() != QNetworkReply::NoError) { qDebug() << reply->errorString() << url; reply->deleteLater(); } else { device = reply; } } if (!device) return; const QByteArray data = device->readAll(); delete device; device = NULL; if (!permissive && imdecode(Mat(1, data.size(), CV_8UC1, (void*)data.data()), IMREAD_ANYDEPTH | IMREAD_ANYCOLOR).empty()) return; const QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); br_append_utemplate_contents(stdout, reinterpret_cast<const unsigned char*>(hash.data()), reinterpret_cast<const unsigned char*>(hash.data()), 3, data.size(), reinterpret_cast<const unsigned char*>(data.data())); if (!metadata.isEmpty()) { const QByteArray metadataHash = QCryptographicHash::hash(metadata, QCryptographicHash::Md5); br_append_utemplate_contents(stdout, reinterpret_cast<const unsigned char*>(hash.data()), reinterpret_cast<const unsigned char*>(metadataHash.data()), 2, metadata.size() + 1 /* include null terminator */, reinterpret_cast<const unsigned char*>(metadata.data())); } }
/** * \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); }
bool readConfFile(QIODevice &device, QSettings::SettingsMap &map) { // Is this the right conversion? const QString& data = QString::fromUtf8(device.readAll().data()); // Split by a RE which should match any platform's line breaking rules QRegExp matchLbr("[\\n\\r]+"); const QStringList& lines = data.split(matchLbr, QString::SkipEmptyParts); //QString currentSection = ""; //QRegExp sectionRe("^\\[(.+)\\]$"); QRegExp keyRe("^([^=]+)\\s*=\\s*(.+)$"); QRegExp cleanComment("#.*$"); QRegExp cleanWhiteSpaces("^\\s+"); QRegExp reg1("\\s+$"); for(int i=0; i<lines.size(); i++) { QString l = lines.at(i); l.replace(cleanComment, ""); // clean comments l.replace(cleanWhiteSpaces, ""); // clean whitespace l.replace(reg1, ""); // Otherwise only process if it macthes an re which looks like: key = value if (keyRe.exactMatch(l)) { // Let REs do the work for us exatracting the key and value // and cleaning them up by removing whitespace QString k = keyRe.cap(1); QString v = keyRe.cap(2); v.replace(cleanWhiteSpaces, ""); k.replace(reg1, ""); // Set the map item. map[k] = QVariant(v); } } return true; }
void startAudioCapture() { if (audioDeviceInfo.isNull()) { audioInput = nullptr; return; } audioInput = std::make_unique<QAudioInput>(audioDeviceInfo, audioFormat); QIODevice * audioDevice = audioInput->start(); audioBuffer.clear(); QObject::connect(audioDevice, &QIODevice::readyRead, audioDevice, [=](){ audioBuffer += audioDevice->readAll(); int frameSize = 1024 * audioFormat.channelCount(); while (audioBuffer.size() > frameSize) { QByteArray data = audioBuffer.left(frameSize); audioBuffer.remove(0, frameSize); writeAudioFrame(audioStreamIndex, data); } }); }
void WebImageView::setUrl(const QUrl url) { if(url != mUrl){ resetImage(); mUrl = url; QIODevice *temp = diskCache->data(url); if(temp){ setImage(Image(temp->readAll())); mLoading = 1; emit loadingChanged(); } else{ mLoading = 0.01; emit loadingChanged(); if(defaultImageUrl!=QUrl("")) setImage(Image(defaultImageUrl)); urls.push_back(url); replies.push_back(mNetManager->get(QNetworkRequest(url))); connect(replies.back(),SIGNAL(finished()), this, SLOT(imageLoaded())); connect(replies.back(),SIGNAL(downloadProgress ( qint64 , qint64 )), this, SLOT(downloadProgressed(qint64,qint64))); } emit urlChanged(); } }
/*! Reads the contents of the text document \a content into \a document. Returns true if the read was successful and false otherwise. */ bool NotesDemo::readContent( QTextDocument *document, QContent *content ) { // Attempt to open the content in read-only mode. If the open succeeds QContent // will construct a new I/O device and return a pointer to it, the caller takes // ownership of the I/O device and is responsible for deleting it. QIODevice *ioDevice = content->open( QIODevice::ReadOnly ); if ( !ioDevice ) { qWarning() << "Could not open the new content object to read from!!"; return false; } QByteArray bytes = ioDevice->readAll(); // Convert the string from an 8-bit ASCII byte array and set it as the plain text // content of the document. document->setPlainText( QString::fromAscii( bytes ) ); // Close the I/O device and destroy it. ioDevice->close(); delete ioDevice; return true; }
void KGameSvgDocument::load() { if (d->m_svgFilename.isNull()) { kDebug(11000) << "KGameSvgDocument::load(): Filename not specified."; return; } QFile file(d->m_svgFilename); if (!file.open(QIODevice::ReadOnly)) { return; } QByteArray content = file.readAll(); // If the file is compressed, decompress the contents before loading it. if (!content.startsWith("<?xml")) { QBuffer buf(&content); QIODevice *flt = KFilterDev::device(&buf, QString::fromLatin1("application/x-gzip"), false); if (!flt || !flt->open(QIODevice::ReadOnly)) { delete flt; return; } QByteArray ar = flt->readAll(); delete flt; content = ar; } if (!setContent(content)) { file.close(); kDebug(11000) << "DOM content not set."; return; } file.close(); }
bool CommandInterface::execute(Request &req, QIODevice &io) { form(req); if(io.isOpen()) { io.readAll(); io.write(req.getBody()); QSerialPort &port = dynamic_cast<QSerialPort&>(io); if(&port != nullptr) { port.flush(); int waitWritePause = (req.getBody().count()*12000.0)/port.baudRate(); waitWritePause+=10; QThread::currentThread()->msleep(waitWritePause); } if(waitAnAnswer(req,io)) { req.setAnswerData(req.getRdData()); if(checkAnAnswer(req)) { getAnAnswer(req); return true; } }else req.setAnswerData(QByteArray()); } return false; }
QByteArray SvgTinter::tint( const QString &filename) { QFile file( filename ); if ( !file.open( QIODevice::ReadOnly ) ) { error() << "Unable to open file: " << filename; return QByteArray(); } QByteArray svg_source( file.readAll() ); // Copied from KSvgrenderer.cpp as we don't load it directly. if (!svg_source.startsWith("<?xml")) { QBuffer buf( &svg_source ); QIODevice *flt = KFilterDev::device( &buf, QString::fromLatin1("application/x-gzip"), false ); if (!flt) return QByteArray(); if (!flt->open(QIODevice::ReadOnly)) { delete flt; return QByteArray(); } svg_source = flt->readAll(); delete flt; } // QString svg_string( svg_source ); QHashIterator<QByteArray, QString> tintIter( m_tintMap ); while( tintIter.hasNext() ) { tintIter.next(); svg_source.replace( tintIter.key(), tintIter.value().toLocal8Bit() ); } return svg_source; }
QByteArray FileDownloader::data(const QUrl & url) { QNetworkDiskCache* cache = qobject_cast<QNetworkDiskCache*>(mNetworkManager->cache()); if (cache) { QIODevice* reader = cache->data(url); if (reader) return reader->readAll(); } return QByteArray(); }