void DownloadItem::metaDataChanged() { if (m_reply->hasRawHeader(QByteArray("Content-Disposition"))) { QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition")); int index = header.indexOf("filename="); if (index >= 0) { header = header.mid(index+9); if (header.startsWith("\"") || header.startsWith("'")) header = header.mid(1); if (header.endsWith("\"") || header.endsWith("'")) header.chop(1); m_fileName = QUrl::fromPercentEncoding(header); } // Sometimes "filename=" and "filename*=UTF-8''" is set. // So, search for this too. index = header.indexOf("filename*=UTF-8''"); if (index >= 0) { header = header.mid(index+17); if (header.startsWith("\"") || header.startsWith("'")) header = header.mid(1); if (header.endsWith("\"") || header.endsWith("'")) header.chop(1); m_fileName = QUrl::fromPercentEncoding(header); } } QVariant statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (!statusCode.isValid()) return; int status = statusCode.toInt(); if (status != 200) { QString reason = m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); qDebug() << reason; } }
QByteArray stripPointerType(QByteArray type) { if (type.endsWith('*')) type.chop(1); if (type.endsWith("* const")) type.chop(7); if (type.endsWith(' ')) type.chop(1); return type; }
QByteArray composePreprocessorOutput(const Symbols &symbols) { QByteArray output; int lineNum = 1; Token last = PP_NOTOKEN; Token secondlast = last; int i = 0; while (hasNext(symbols, i)) { Symbol sym = next(symbols, i); switch (sym.token) { case PP_NEWLINE: case PP_WHITESPACE: if (last != PP_WHITESPACE) { secondlast = last; last = PP_WHITESPACE; output += ' '; } continue; case PP_STRING_LITERAL: if (last == PP_STRING_LITERAL) output.chop(1); else if (secondlast == PP_STRING_LITERAL && last == PP_WHITESPACE) output.chop(2); else break; output += sym.lexem().mid(1); secondlast = last; last = PP_STRING_LITERAL; continue; case MOC_INCLUDE_BEGIN: lineNum = 0; continue; case MOC_INCLUDE_END: lineNum = sym.lineNum; continue; default: break; } secondlast = last; last = sym.token; const int padding = sym.lineNum - lineNum; if (padding > 0) { output.resize(output.size() + padding); memset(output.data() + output.size() - padding, '\n', padding); lineNum = sym.lineNum; } output += sym.lexem(); } return output; }
QByteArray Cipher::parseInitKeyX(QByteArray key) { QCA::Initializer init; bool isCBC = false; if (key.endsWith(" CBC")) { isCBC = true; key.chop(4); } if (key.length() != 181) return QByteArray(); QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH(); if (privateKey.isNull()) return QByteArray(); QByteArray publicKey = privateKey.y().toArray().toByteArray(); // remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return QByteArray(); QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); // remove trailing = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); if (isCBC) sharedKey.prepend("cbc:"); bool success = setKey(sharedKey); if (!success) return QByteArray(); return publicKey.toBase64().append('A'); }
bool Cipher::parseFinishKeyX(QByteArray key) { QCA::Initializer init; if (key.length() != 181) return false; QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return false; if (m_tempKey.isNull()) return false; QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); // remove trailng = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); bool success = setKey(sharedKey); return success; }
QList<QByteArray> TSVFileStream::readLine() { //handle first content line if (!next_line_.isNull()) { if (next_line_=="") { next_line_ = QByteArray(); return QList<QByteArray>(); } QList<QByteArray> parts = next_line_.split(separator_); if (parts.count()!=columns_) { THROW(FileParseException, "Expected " + QString::number(columns_) + " columns, but got " + QString::number(parts.count()) + " columns in line 1 of file " + filename_); } next_line_ = QByteArray(); return parts; } //handle second to last content line QByteArray line = file_.readLine(); while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); ++line_; if (line=="") { return QList<QByteArray>(); } QList<QByteArray> parts = line.split(separator_); if (parts.count()!=columns_) { THROW(FileParseException, "Expected " + QString::number(columns_) + " columns, but got " + QString::number(parts.count()) + " columns in line " + QString::number(line_) + " of file " + filename_); } return parts; }
MozPaster::MozPaster(AnimatedWindow *parent) : AnimatedWindow(parent), ui(new Ui::MozPaster), nam (new QNetworkAccessManager(this)) { ui->setupUi(this); ui->plainTextEdit->setFocus(); resize (500, 400); /// QFile fp (":/resources/data/types"); if (fp.open(QIODevice::ReadOnly | QIODevice::Text)) { while (! fp.atEnd()) { QByteArray line = fp.readLine(); line.chop(1); ui->comboBox->addItem(line); } } connect (nam , SIGNAL(finished(QNetworkReply*)) , SLOT(finished(QNetworkReply*))); }
QByteArray TransformAbstract::fromHex(QByteArray in) { QString invalid; QString HEXCHAR("abcdefABCDEF0123456789"); for (int i = 0; i < in.size(); i++) { if (!HEXCHAR.contains(in.at(i))) { if (!invalid.contains(in.at(i))) invalid.append(in.at(i)); } } if (!invalid.isEmpty()) { emit error(tr("Invalid character(s) found in the hexadecimal stream: '%1', they will be skipped").arg(invalid),name()); } in.replace(invalid,""); if (in.size()%2 != 0) { in.chop(1); emit error(tr("Invalid size for a hexadecimal stream, skipping the last byte."),name()); } return QByteArray::fromHex(in); }
void NtgTransformDomainNameToIp::_parseOutput() { _setProgress(50.0, "Parsing output..."); QList<NtgEntity> results; QByteArray line; while( ! _process.atEnd()) { if(_process.canReadLine()) { line = _process.readLine(); if(line.startsWith("Name:")) { if(_process.canReadLine()) { line = _process.readLine(); line = line.mid(9);line.chop(1); qDebug() << "IP: " << line; QHash<QString,QString> values; values["value"] = line; NtgEntity e("ip-address", values ); results.append(e); } else { // incomplete IP line, unget Name line ungetLine(&_process, line); break; } } } } _addResults(results); _setProgress(100.0, "Finished"); }
void OwncloudDolphinPluginHelper::slotReadyRead() { while (_socket.bytesAvailable()) { _line += _socket.readLine(); if (!_line.endsWith("\n")) continue; QByteArray line; qSwap(line, _line); line.chop(1); if (line.isEmpty()) continue; if (line.startsWith("REGISTER_PATH:")) { auto col = line.indexOf(':'); QString file = QString::fromUtf8(line.constData() + col + 1, line.size() - col - 1); _paths.append(file); continue; } else if (line.startsWith("STRING:")) { auto args = QString::fromUtf8(line).split(QLatin1Char(':')); if (args.size() >= 3) { _strings[args[1]] = args.mid(2).join(QLatin1Char(':')); } continue; } emit commandRecieved(line); } }
void testPutSequential() { #if defined(USE_QNAM) && QT_VERSION <= QT_VERSION_CHECK(5, 5, 0) QSKIP("This test is broken with Qt < 5.5, the fix is 9286a8e5dd97c5d4d7e0ed07a73d4ce7240fdc1d in qtbase"); #endif const QString aDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation); QVERIFY(QDir::temp().mkpath(aDir)); const QString aFile = aDir + QStringLiteral("/accessmanagertest-data2"); const QString putDataContents = "We love free software! " + QString(24000, 'c'); QProcess process; process.start(QStringLiteral("echo"), QStringList() << putDataContents); QFile::remove(aFile); QNetworkReply *reply = manager()->put(QNetworkRequest(QUrl::fromLocalFile(aFile)), &process); QSignalSpy spy(reply, SIGNAL(finished())); QVERIFY(spy.wait()); QVERIFY(QFile::exists(aFile)); QFile f(aFile); QVERIFY(f.open(QIODevice::ReadOnly)); QByteArray cts = f.readAll(); cts.chop(1); //we remove the eof QCOMPARE(QString::fromUtf8(cts).size(), putDataContents.size()); QCOMPARE(QString::fromUtf8(cts), putDataContents); QFile::remove(aFile); }
void Binary::transform(const QByteArray &input, QByteArray &output) { output.clear(); if (input.isEmpty()) return; QByteArray temp; if (wayValue == TransformAbstract::INBOUND) { for (int i = 0; i < input.size(); i++) { temp = QByteArray::number((uchar)(input.at(i)), 2); if (temp.size() < 8) { int count = temp.size(); for (int j = 0; j < 8 - count ; j++) temp.prepend("0"); } output.append(temp); } if (blockSize != 0) { temp = output; output.clear(); for (int i = 0; i < temp.size(); i += blockSize) { output.append(temp.mid(i, blockSize)).append(' '); } output.chop(1); } } else { bool ok = false; for (int i = 0; i < input.size(); i++) { if (BINARYCHAR.contains(input.at(i))) { temp.append(input.at(i)); } else { ok = false; } } if (!ok) emit warning(tr("Invalid characters have been found, they have been ignored."),id); int length = (temp.size() / 8) * 8; int rest = temp.size() % 8; bool errors = false; for (int i = 0; i < length; i += 8) { char ch = char(temp.mid(i,8).toUShort(&ok,2)); if (ok) output.append(ch); else { errors = true; output.append(temp.mid(i,8)); } } if (rest != 0) { output.append(temp.mid(length,rest)); emit warning(tr("Length is not a multiple of 8, ignoring the last bit(s)"),id); } if (errors) emit error(tr("Errors were encountered during the process, faulty blocks have been skipped."),id); } }
bool Nuria::Serializer::writeField (void *object, Nuria::MetaField &field, const QVariantMap &data) { QVariant value = data.value (QString::fromLatin1 (field.name ())); QByteArray typeName = field.typeName (); bool isPointer = typeName.endsWith ('*'); bool ignored = false; int pointerId = 0; if (isPointer) { pointerId = QMetaType::type (typeName.constData ()); typeName.chop (1); } int sourceId = value.userType (); int targetId = QMetaType::type (typeName.constData ()); if (sourceId != targetId && targetId != QMetaType::QVariant) { variantToField (value, typeName, targetId, sourceId, pointerId, ignored); if (ignored) { return true; } } if ((isPointer && value.isValid ()) || value.userType () == targetId || targetId == QMetaType::QVariant) { return field.write (object, value); } // return false; }
// Save unfinished time MPlayer::~MPlayer() { #ifdef Q_OS_LINUX if (!unfinished_time.isEmpty() && Settings::rememberUnfinished) { QByteArray data; QHash<QString, int>::const_iterator i = unfinished_time.constBegin(); while (i != unfinished_time.constEnd()) { QString name = i.key(); if (!name.startsWith("http://")) data += name.toUtf8() + '\n' + QByteArray::number(i.value()) + '\n'; i++; } data.chop(1); // Remove last '\n' if (data.isEmpty()) return; QString filename = QDir::homePath() + "/.moonplayer/unfinished.txt"; QFile file(filename); if (!file.open(QFile::WriteOnly)) return; file.write(data); file.close(); } else { QDir dir = QDir::home(); dir.cd(".moonplayer"); if (dir.exists("unfinished.txt")) dir.remove("unfinished.txt"); } #endif }
bool KBModel::dropMimeData(const QMimeData* mime, Qt::DropAction action, int row, int col, const QModelIndex& parent) { if (action == Qt::IgnoreAction) return true; if (!mime->hasFormat("application/lain.local_binary_objects")) return false; QByteArray encodedData = mime->data("application/lain.local_binary_objects"); QByteArray dt = encodedData; dt.append(' '); dt.chop(1); QDataStream stream(&dt, QIODevice::ReadOnly); QString text; while (!stream.atEnd()) { tnode_t tnode; stream >> tnode; tnode = db_->tnodeman()->locate(tnode.idx); text += "Tnode: "; text += QString::number(tnode.idx); text += "\t"; text += tnode.mastername; text += "\n"; } QMessageBox::information(NULL, tr("Drop!"), text); return true; }
bool AmosePluginsManager::loadPlugins() { ABSTRACTFACTORYPATTERNLOGINIT; LINFO << "AmosePluginsManager::loadPlugins"; // DynamicLibrariesManager::changeable().addSearchPath("c:\amose\lib");; // open LIMA_CONF/plugins file QDir pluginsDir(QString::fromUtf8(qgetenv("LIMA_CONF").constData()==0?"":qgetenv("LIMA_CONF").constData()) + "/plugins"); QStringList pluginsFiles = pluginsDir.entryList(QDir::Files); Q_FOREACH(QString pluginsFile, pluginsFiles) { LINFO << "AmosePluginsManager::loadPlugins loding plugins file " << pluginsFile.toUtf8().data(); QFile file(pluginsDir.path() + "/" + pluginsFile); if (!file.open(QIODevice::ReadOnly)) return false; // for each entry, call load library while (!file.atEnd()) { QByteArray line = file.readLine(); if (line.endsWith('\n')) line.chop(1); // Allows empty and comment lines if ( !line.isEmpty() && !line.startsWith('#') ) { #ifdef WIN32 QString strline = QString(line.data()) + ".dll"; #else QString strline = QString("lib") + line.data() + ".so"; #endif LDEBUG << "AmosePluginsManager::loadPlugins loading plugin '" << line.data() << "'"; DynamicLibrariesManager::changeable().loadLibrary(line.data()); } } }
void OwncloudDolphinPluginHelper::slotReadyRead() { while (_socket.bytesAvailable()) { _line += _socket.readLine(); if (!_line.endsWith("\n")) continue; QByteArray line; qSwap(line, _line); line.chop(1); if (line.isEmpty()) continue; if (line.startsWith("REGISTER_PATH:")) { auto col = line.indexOf(':'); QString file = QString::fromUtf8(line.constData() + col + 1, line.size() - col - 1); _paths.append(file); continue; } else if (line.startsWith("SHARE_MENU_TITLE:")) { auto col = line.indexOf(':'); _shareActionString = QString::fromUtf8(line.constData() + col + 1, line.size() - col - 1); continue; } emit commandRecieved(line); } }
QStringList Helper::loadTextFile(QSharedPointer<QFile> file, bool trim_lines, QChar skip_header_char, bool skip_empty_lines) { QStringList output; while (!file->atEnd()) { QByteArray line = file->readLine(); //remove newline or trim if (trim_lines) { line = line.trimmed(); } else { while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); } //skip empty lines if (skip_empty_lines && line.count()==0) continue; //skip header lines if (skip_header_char!=QChar::Null && line.count()!=0 && line[0]==skip_header_char.toLatin1()) continue; output.append(line); } return output; }
/** * Redirects the standard output (prime numbers or prime k-tuplets) of * the primeSieveProcess_ to the TextEdit. */ void PrimeSieveGUI::printProcessOutput() { QByteArray buffer; buffer.reserve(PRINT_BUFFER_SIZE + 256); while (ui->cancelButton->isEnabled() && primeSieveProcess_->canReadLine()) { buffer.clear(); while (primeSieveProcess_->canReadLine() && buffer.size() < PRINT_BUFFER_SIZE) buffer.append(primeSieveProcess_->readLine(256)); // remove "\r\n" or '\n', '\r' at the back while (buffer.endsWith('\n') || buffer.endsWith('\r')) buffer.chop(1); if (!buffer.isEmpty()) ui->textEdit->appendPlainText(buffer); /// @brief Keep the GUI responsive. /// @bug processEvents() crashes on Windows with MSVC 2010 and Qt 5 beta. /// @warning QApplication::processEvents() must not be used on /// operating systems that use signal recursion (like Linux /// X11) otherwise the stack will explode! #if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_IOS) QApplication::processEvents(); #else ui->textEdit->repaint(); #endif } }
void Moc::parseDeclareMetatype() { next(LPAREN); QByteArray typeName = lexemUntil(RPAREN); typeName.remove(0, 1); typeName.chop(1); metaTypes.append(typeName); }
QByteArray TwitterDataUtil::authorizationHeader(const QByteArray &oauthConsumerKey, const QByteArray &oauthConsumerSecret, const QByteArray &requestMethod, const QByteArray &requestUrl, const std::vector<std::pair<QByteArray, QByteArray>> ¶meters, const QByteArray &oauthToken, const QByteArray &oauthTokenSecret, const QByteArray &oauthNonce, const QByteArray &oauthTimestamp) { // Twitter requires all requests to be signed with an authorization header. QByteArray nonce {oauthNonce}; if (nonce.isEmpty()) { nonce = QUuid::createUuid().toByteArray().toBase64(); } QByteArray timestamp {oauthTimestamp}; if (timestamp.isEmpty()) { timestamp = QByteArray::number(qFloor(QDateTime::currentMSecsSinceEpoch() / 1000.0)); } // now build up the encoded parameters map. We use a map to perform alphabetical sorting. QMap<QByteArray, QByteArray> encodedParams {}; encodedParams.insert(QByteArray("oauth_consumer_key").toPercentEncoding(), QByteArray(oauthConsumerKey).toPercentEncoding()); encodedParams.insert(QByteArray("oauth_nonce").toPercentEncoding(), nonce.toPercentEncoding()); encodedParams.insert(QByteArray("oauth_signature_method").toPercentEncoding(), QByteArray(OAUTH_SIGNATURE_METHOD).toPercentEncoding()); encodedParams.insert(QByteArray("oauth_timestamp").toPercentEncoding(), timestamp.toPercentEncoding()); encodedParams.insert(QByteArray("oauth_version").toPercentEncoding(), QByteArray(OAUTH_VERSION).toPercentEncoding()); if (!oauthToken.isEmpty()) { encodedParams.insert(QByteArray("oauth_token").toPercentEncoding(), oauthToken.toPercentEncoding()); } for (const std::pair<QByteArray, QByteArray> ¶meter : parameters) { encodedParams.insert(parameter.first, parameter.second); } QByteArray parametersByteArray {}; QList<QByteArray> keys = encodedParams.keys(); for (const QByteArray &key : keys) { parametersByteArray += key + QByteArray("=") + encodedParams.value(key) + QByteArray("&"); } parametersByteArray.chop(1); QByteArray signatureBaseString {requestMethod.toUpper() + QByteArray("&") + requestUrl.toPercentEncoding() + QByteArray("&") + parametersByteArray.toPercentEncoding()}; QByteArray signingKey {oauthConsumerSecret.toPercentEncoding() + QByteArray("&") + oauthTokenSecret.toPercentEncoding()}; QByteArray oauthSignature {QMessageAuthenticationCode::hash(signatureBaseString, signingKey, QCryptographicHash::Sha1).toBase64()}; encodedParams.insert(QByteArray("oauth_signature").toPercentEncoding(), oauthSignature.toPercentEncoding()); // now generate the Authorization header from the encoded parameters map. // we need to remove the query items from the encoded parameters map first. QByteArray authHeader = QByteArray("OAuth "); for (const std::pair<QByteArray, QByteArray> ¶meter : parameters) { encodedParams.remove(parameter.first); } keys = encodedParams.keys(); foreach (const QByteArray &key, keys) { authHeader += key + "=\"" + encodedParams.value(key) + "\", "; }
void RfcommClient::serverReplied() { while (socket->canReadLine()) { QByteArray line = socket->readLine(); line.chop(2); logArea->append(QString(tr("From server: %1")) .arg(QString(line))); } }
static void qSignalDumperCallback(QObject *caller, int method_index, void **argv) { Q_ASSERT(caller); Q_ASSERT(argv); Q_UNUSED(argv); const QMetaObject *mo = caller->metaObject(); Q_ASSERT(mo); QMetaMethod member = mo->method(method_index); Q_ASSERT(member.signature()); if (QTest::ignoreClasses() && QTest::ignoreClasses()->contains(mo->className())) { ++QTest::ignoreLevel; return; } QByteArray str; str.fill(' ', QTest::iLevel++ * QTest::IndentSpacesCount); str += "Signal: "; str += mo->className(); str += '('; QString objname = caller->objectName(); str += objname.toLocal8Bit(); if (!objname.isEmpty()) str += ' '; str += QByteArray::number(quintptr(caller), 16); str += ") "; str += QTest::memberName(member); str += " ("; QList<QByteArray> args = member.parameterTypes(); for (int i = 0; i < args.count(); ++i) { const QByteArray &arg = args.at(i); int typeId = QMetaType::type(args.at(i).constData()); if (arg.endsWith('*') || arg.endsWith('&')) { str += '('; str += arg; str += ')'; if (arg.endsWith('&')) str += '@'; quintptr addr = quintptr(*reinterpret_cast<void **>(argv[i + 1])); str.append(QByteArray::number(addr, 16)); } else if (typeId != QMetaType::Void) { str.append(arg) .append('(') .append(QVariant(typeId, argv[i + 1]).toString().toLocal8Bit()) .append(')'); } str.append(", "); } if (str.endsWith(", ")) str.chop(2); str.append(')'); qPrintMessage(str); }
void Moc::parseSignals(ClassDef *def) { int defaultRevision = -1; if (test(Q_REVISION_TOKEN)) { next(LPAREN); QByteArray revision = lexemUntil(RPAREN); revision.remove(0, 1); revision.chop(1); bool ok = false; defaultRevision = revision.toInt(&ok); if (!ok || defaultRevision < 0) error("Invalid revision"); } next(COLON); while (inClass(def) && hasNext()) { switch (next()) { case PUBLIC: case PROTECTED: case PRIVATE: case Q_SIGNALS_TOKEN: case Q_SLOTS_TOKEN: prev(); return; case SEMIC: continue; case FRIEND: until(SEMIC); continue; case USING: error("'using' directive not supported in 'signals' section"); default: prev(); } FunctionDef funcDef; funcDef.access = FunctionDef::Protected; parseFunction(&funcDef); if (funcDef.isVirtual) warning("Signals cannot be declared virtual"); if (funcDef.inlineCode) error("Not a signal declaration"); if (funcDef.revision > 0) { ++def->revisionedMethods; } else if (defaultRevision != -1) { funcDef.revision = defaultRevision; ++def->revisionedMethods; } def->signalList += funcDef; while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) { funcDef.wasCloned = true; funcDef.arguments.removeLast(); def->signalList += funcDef; } } }
QT_BEGIN_NAMESPACE /*! \internal Decode a data: URL into its mimetype and payload. Returns a null string if the URL could not be decoded. */ Q_CORE_EXPORT QPair<QString, QByteArray> qDecodeDataUrl(const QUrl &uri) { QString mimeType; QByteArray payload; if (uri.scheme() == QLatin1String("data") && uri.host().isEmpty()) { mimeType = QLatin1String("text/plain;charset=US-ASCII"); // the following would have been the correct thing, but // reality often differs from the specification. People have // data: URIs with ? and # //QByteArray data = QByteArray::fromPercentEncoding(uri.encodedPath()); QByteArray data = QByteArray::fromPercentEncoding(uri.toEncoded()); // remove the data: scheme data.remove(0, 5); // parse it: int pos = data.indexOf(','); if (pos != -1) { payload = data.mid(pos + 1); data.truncate(pos); data = data.trimmed(); // find out if the payload is encoded in Base64 if (data.endsWith(";base64")) { payload = QByteArray::fromBase64(payload); data.chop(7); } if (data.toLower().startsWith("charset")) { int i = 7; // strlen("charset") while (data.at(i) == ' ') ++i; if (data.at(i) == '=') data.prepend("text/plain;"); } if (!data.isEmpty()) mimeType = QLatin1String(data.trimmed()); } } return QPair<QString,QByteArray>(mimeType,payload); }
void RuleGraph::dump_impl(QByteArray &indent, int rootIndex) const { const RuleConstPtr r = m_rules[rootIndex]; printf("%s", indent.constData()); printf("%s", qPrintable(r->toString())); printf("\n"); indent.append(" "); for (int childIndex : qAsConst(m_children[rootIndex])) dump_impl(indent, childIndex); indent.chop(2); }
void IdentServer::respond() { auto* socket = qobject_cast<QTcpSocket*>(sender()); Q_ASSERT(socket); qint64 transactionId = _socketId; if (!socket->canReadLine()) { return; } QByteArray query = socket->readLine(); if (query.endsWith("\r\n")) query.chop(2); else if (query.endsWith("\n")) query.chop(1); QList<QByteArray> split = query.split(','); bool success = false; quint16 localPort = 0; if (!split.empty()) { localPort = split[0].trimmed().toUShort(&success, 10); } Request request{socket, localPort, query, transactionId, _requestId++}; if (!success) { request.respondError("INVALID-PORT"); } else if (responseAvailable(request)) { // success } else if (lowestSocketId() < transactionId) { _requestQueue.emplace_back(request); } else { request.respondError("NO-USER"); } }
QByteArray PgpManager::SignMessage (const QByteArray& body) { QCA::SecureMessageKey msgKey; if (PrivateKey_.isNull ()) { warning (QString ("Cannot sign: private key is null")); return QByteArray (); } msgKey.setPGPSecretKey (PrivateKey_); QCA::OpenPGP pgp; QCA::SecureMessage msg (&pgp); msg.setFormat (QCA::SecureMessage::Ascii); msg.setSigner (msgKey); msg.startSign (QCA::SecureMessage::Detached); msg.update (body); msg.end (); msg.waitForFinished (); if (!msg.success ()) { warning (QString { "Error signing: %1 (%2)." } .arg (msg.errorCode ()) .arg (msg.diagnosticText ())); return QByteArray (); } const auto& sig = msg.signature (); const auto& arrs = sig.split ('\n'); auto it = arrs.begin (); ++it; if (it == arrs.end ()) return sig; for (; it != arrs.end (); ++it) if (it->isEmpty ()) break; if (++it >= arrs.end ()) return sig; QByteArray result; for (; it != arrs.end (); ++it) { if (it->at (0) == '-') break; result += *it; result += '\n'; } result.chop (1); return result; }
// Helper for xmlBufferCompare static bool textBufferCompare( const QByteArray& source, const QByteArray& dest, // for the qDebug only QIODevice& sourceFile, QIODevice& destFile) { int lineNumber = 1; while (!sourceFile.atEnd()) { if (destFile.atEnd()) return false; QByteArray sourceLine = sourceFile.readLine(); QByteArray destLine = destFile.readLine(); if (sourceLine != destLine) { sourceLine.chop(1); // remove '\n' destLine.chop(1); // remove '\n' qDebug() << source << "and" << dest << "differ at line" << lineNumber; qDebug("got : %s", sourceLine.constData()); qDebug("expected: %s", destLine.constData()); return false; } ++lineNumber; } return true; }
// --- Input and Output ---------------------------------------------------- // bool MdlFileFormat::read(std::istream &input, chemkit::MoleculeFile *file) { QByteArray data; while(!input.eof()){ data += input.get(); } data.chop(1); QBuffer buffer; buffer.setData(data); buffer.open(QBuffer::ReadOnly); return read(&buffer, file); }