bool QQnxButtonEventNotifier::parsePPS(const QByteArray &ppsData, QHash<QByteArray, QByteArray> *messageFields) const
{
    // tokenize pps data into lines
    QList<QByteArray> lines = ppsData.split('\n');

    // validate pps object
    if (lines.size() == 0 || !lines.at(0).contains(QByteArrayLiteral("@status"))) {
        qWarning("QQNX: unrecognized pps object, data=%s", ppsData.constData());
        return false;
    }

    // parse pps object attributes and extract values
    for (int i = 1; i < lines.size(); i++) {

        // tokenize current attribute
        const QByteArray &attr = lines.at(i);

        qButtonDebug() << Q_FUNC_INFO << "attr=" << attr;

        int doubleColon = attr.indexOf(QByteArrayLiteral("::"));
        if (doubleColon == -1) {
            // abort - malformed attribute
            continue;
        }

        QByteArray key = attr.left(doubleColon);
        QByteArray value = attr.mid(doubleColon + 2);
        messageFields->insert(key, value);
    }
    return true;
}
TSession TSessionCookieStore::find(const QByteArray &id)
{
    TSession session;
    if (id.isEmpty())
        return session;

    QList<QByteArray> balst = id.split('_');
    if (balst.count() == 2 && !balst.value(0).isEmpty() && !balst.value(1).isEmpty()) {
        QByteArray ba = QByteArray::fromHex(balst.value(0));
        QByteArray digest = QCryptographicHash::hash(ba + Tf::appSettings()->value(Tf::SessionSecret).toByteArray(),
                                                     QCryptographicHash::Sha1);

        if (digest != QByteArray::fromHex(balst.value(1))) {
            tSystemWarn("Recieved a tampered cookie or that of other web application.");
            //throw SecurityException("Tampered with cookie", __FILE__, __LINE__);
            return session;
        }

        QDataStream ds(&ba, QIODevice::ReadOnly);
        ds >> *static_cast<QVariantMap *>(&session);

        if (ds.status() != QDataStream::Ok) {
            tSystemError("Unable to load a session from the cookie store.");
            session.clear();
        }
    }
Esempio n. 3
0
QUrl LocalRedirectServer::ParseUrlFromRequest(const QByteArray& request) const {
  QList<QByteArray> lines = request.split('\r');
  const QByteArray& request_line = lines[0];
  QByteArray path = request_line.split(' ')[1];
  QUrl base_url = url();
  QUrl request_url(base_url.toString() + path.mid(1), QUrl::StrictMode);
  return request_url;
}
Esempio n. 4
0
/**
 * for now our data is just the MAC address of the default gateway
 */
NetworkLocation NetworkLocation::currentLocation()
{
    QProcess ip;
    ip.start("/sbin/ip", QStringList() << "route");

    if (!ip.waitForStarted())
        return NetworkLocation();

    if (!ip.waitForFinished())
        return NetworkLocation();

    QByteArray gwIp;
    while (ip.canReadLine()) {
        QByteArray line = ip.readLine();
        if (line.startsWith("default")) {
            QList<QByteArray> parts = line.split(' ');
            gwIp = parts[2];
            break;
        }
    }
    if (gwIp.isEmpty())
            return NetworkLocation();

    QProcess arp;
    arp.start("/sbin/arp", QStringList() << "-a");

    if (!arp.waitForStarted())
        return NetworkLocation();

    if (!arp.waitForFinished())
        return NetworkLocation();

    QByteArray gwMAC;
    while (arp.canReadLine()) {
        QByteArray line = arp.readLine();
        if (line.contains(gwIp)) {
            QList<QByteArray> parts = line.split(' ');
            gwMAC = parts[3];
            break;
        }
    }
    if (gwMAC.isEmpty())
        return NetworkLocation();

    return NetworkLocation(gwMAC);
}
Exchange_Bitstamp::Exchange_Bitstamp(QByteArray pRestSign, QByteArray pRestKey)
	: Exchange()
{
	checkDuplicatedOID=true;
	accountFee=0.0;
	balanceDisplayAvailableAmount=false;
	minimumRequestIntervalAllowed=1200;
	calculatingFeeMode=1;
	isLastTradesTypeSupported=false;
	exchangeSupportsAvailableAmount=true;
	lastBidAskTimestamp=0;
	lastTradesDate=0;
	lastTickerDate=0;
	baseValues.exchangeName="Bitstamp";
	baseValues.currentPair.name="BTC/USD";
	baseValues.currentPair.setSymbol("BTCUSD");
	baseValues.currentPair.currRequestPair="BTCUSD";
	baseValues.currentPair.priceDecimals=2;
	baseValues.currentPair.priceMin=qPow(0.1,baseValues.currentPair.priceDecimals);
	baseValues.currentPair.tradeVolumeMin=0.01;
	baseValues.currentPair.tradePriceMin=0.1;
	depthAsks=0;
	depthBids=0;
	forceDepthLoad=false;
	julyHttp=0;
	tickerOnly=false;
	privateRestSign=pRestSign;
	privateRestKey=pRestKey.split(':').last();
	privateClientId=pRestKey.split(':').first();

	currencyMapFile="Bitstamp";
	defaultCurrencyParams.currADecimals=8;
	defaultCurrencyParams.currBDecimals=5;
	defaultCurrencyParams.currABalanceDecimals=8;
	defaultCurrencyParams.currBBalanceDecimals=5;
	defaultCurrencyParams.priceDecimals=2;
	defaultCurrencyParams.priceMin=qPow(0.1,baseValues.currentPair.priceDecimals);

	supportsLoginIndicator=true;
	supportsAccountVolume=false;
	supportsExchangeLag=false;

	moveToThread(this);
	authRequestTime.restart();
	privateNonce=(static_cast<quint32>(time(NULL))-1371854884)*10;
}
Esempio n. 6
0
bool RecvFileTransfer::parseHeader(QByteArray &recvBlock, struct TransferFile &transferFile)
{
    bool ok;
    int headerSize
        = recvBlock.left(TRANSFER_FILE_HEADER_SIZE_LENGTH).toInt(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get headerSize error";
        return false;
    }

    QByteArray header = recvBlock.left(headerSize);

    QList<QByteArray> list = header.split(':');

#define TRANSFERFILE_NAME_POS           1
#define TRANSFERFILE_SIZE_POS           2
#define TRANSFERFILE_TYPE_POS           3
#define TRANSFERFILE_ATTR_BEGIN_POS     4

    // XXX NOTE: canParseHeader() make sure we have enough items in list,
    // so we do not need to check size of list before call list.at()
//    transferFile.name = Macai::transferCodec->codec()->toUnicode(list.at(TRANSFERFILE_NAME_POS));
    QTextCodec* codec = QTextCodec::codecForName("SYSTEM");
    transferFile.name = codec->toUnicode(list.at(TRANSFERFILE_NAME_POS));

    transferFile.size = list.at(TRANSFERFILE_SIZE_POS).toLongLong(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get file size error";
        return false;
    }
    transferFile.type = list.at(TRANSFERFILE_TYPE_POS).toInt(&ok, 16);
    if (!ok)
    {
        m_errorString = "RecvFileTransfer::parseHeader: get file type error";
        return false;
    }

    // Extended file attribution like mtime, atime...
    for (int i = TRANSFERFILE_ATTR_BEGIN_POS; i < list.size(); ++i)
    {
        QString s = list.at(i);
        QStringList l = s.split(QChar('='));
        if (l.size() == 2)
        {
            int i = l.at(0).toInt(&ok, 16);
            if (ok)
            {
                transferFile.extendAttr.insert(i, l.at(1));
            }
        }
    }

    recvBlock.remove(0, headerSize);

    return true;
}
Esempio n. 7
0
	virtual void main()
	{
		//init
		bool v = getFlag("v");

		//load ids and lengths
		QHash<QByteArray, int> ids;
		QSharedPointer<QFile> file = Helper::openFileForReading(getInfile("ids"));
		while (!file->atEnd())
		{
			QByteArray line = file->readLine().trimmed();
			if (line.isEmpty() || line[0]=='#') continue;
			QList<QByteArray> parts = line.split('\t');
			int length = -1;
			if (parts.count()>1)
			{
				length = Helper::toInt(parts[1], "length value");
			}
			ids.insert(parts[0], length);
		}

		//open output stream
		FastqOutfileStream outfile(getOutfile("out"), false);

		//parse input and write output
		FastqFileStream stream(getInfile("in"));
		FastqEntry entry;
		while (!stream.atEnd())
		{
			stream.readEntry(entry);

			QByteArray id = entry.header.trimmed();
			id = id.mid(1);
			int comment_start = id.indexOf(' ');
			if (comment_start!=-1) id = id.left(comment_start);
			int length = ids.value(id, -2);
			if (length==-2) //id not in list
			{
				if (!v) continue;

				outfile.write(entry);
			}
			else if (length==-1) //id is in list, but no length given
			{
				if (v) continue;

				outfile.write(entry);
			}
			else if (length>=1) //id is in list and length given
			{
				if (v) continue;

				entry.bases.resize(length);
				entry.qualities.resize(length);
				outfile.write(entry);
			}
		}
	}
Esempio n. 8
0
bool EglWaylandBackend::initRenderingContext()
{
    initBufferConfigs();

#ifdef KWIN_HAVE_OPENGLES
    const EGLint context_attribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs);
#else
    const EGLint context_attribs_31_core[] = {
        EGL_CONTEXT_MAJOR_VERSION_KHR, 3,
        EGL_CONTEXT_MINOR_VERSION_KHR, 1,
        EGL_CONTEXT_FLAGS_KHR,         EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR,
        EGL_NONE
    };

    const EGLint context_attribs_legacy[] = {
        EGL_NONE
    };

    const QByteArray eglExtensions = eglQueryString(m_display, EGL_EXTENSIONS);
    const QList<QByteArray> extensions = eglExtensions.split(' ');

    // Try to create a 3.1 core context
    if (options->glCoreProfile() && extensions.contains("EGL_KHR_create_context"))
        m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs_31_core);

    if (m_context == EGL_NO_CONTEXT)
        m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs_legacy);
#endif

    if (m_context == EGL_NO_CONTEXT) {
        qCritical() << "Create Context failed";
        return false;
    }

    if (!m_wayland->surface()) {
        return false;
    }

    const QSize &size = m_wayland->shellSurfaceSize();
    m_overlay = wl_egl_window_create(m_wayland->surface(), size.width(), size.height());
    if (!m_overlay) {
        qCritical() << "Creating Wayland Egl window failed";
        return false;
    }

    m_surface = eglCreateWindowSurface(m_display, m_config, m_overlay, NULL);
    if (m_surface == EGL_NO_SURFACE) {
        qCritical() << "Create Window Surface failed";
        return false;
    }

    return makeContextCurrent();
}
Esempio n. 9
0
void FramePlaybackWindow::loadFilters()
{
    QString filename;
    QFileDialog dialog(this);

    QStringList filters;
    filters.append(QString(tr("Filter List (*.ftl)")));

    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.setNameFilters(filters);
    dialog.setViewMode(QFileDialog::Detail);

    if (dialog.exec() == QDialog::Accepted)
    {
        filename = dialog.selectedFiles()[0];
        //right now there is only one file type that can be loaded here so just do it.
        QFile *inFile = new QFile(filename);
        QByteArray line;
        int ID;
        bool checked = false;

        if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
            return;

        btnSelectNoneClick();

        while (!inFile->atEnd()) {
            line = inFile->readLine().simplified();
            if (line.length() > 2)
            {
                QList<QByteArray> tokens = line.split(',');
                ID = tokens[0].toInt(NULL, 16);
                if (tokens[1].toUpper() == "T") checked = true;
                    else checked = false;
                if (checked)
                {
                    QHash<int,bool>::iterator it;
                    for (it = currentSeqItem->idFilters.begin(); it != currentSeqItem->idFilters.end(); ++it)
                    {
                        if (it.key() == ID)
                        {
                            it.value() = true;
                        }
                    }
                    for (int c = 0; c < ui->listID->count(); c++)
                    {
                        QListWidgetItem *item = ui->listID->item(c);
                        if (item->text().toInt(NULL, 16) == ID)
                        {
                            item->setCheckState(Qt::Checked);
                        }
                    }
                }
            }
        }
        inFile->close();
    }
}
Esempio n. 10
0
void DataLayer::loadDataFromFile()
{
    QFile file(_DATAFILE);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QList<QObject*> Appointments;
    QString nextDay;
    QString prevDay;

    if(!file.atEnd())
    {
        QByteArray otherDayLine = file.readLine();
        QList<QByteArray> otherDays = otherDayLine.split('\t');

        if (otherDays.size()==2)
        {
            nextDay = otherDays.at(0);
            prevDay = otherDays.at(1);
        }
        else
        {
            return;
        }

        while (!file.atEnd())
        {
            QString desc,time,place,link;

            QByteArray line = file.readLine();
            QList<QByteArray> data = line.split('\t');

            if (data.size()>=4)
            {
                desc = QString(data.at(0));
                time = QString(data.at(1));
                place = QString(data.at(2));
                link = QString(data.at(3));

                Appointments.push_back(new Termin(desc,time,place,link));
            }
        }
    }
    setDataModel(new Day(Appointments,nextDay,prevDay));
}
Esempio n. 11
0
static jboolean startQtApplication(JNIEnv *env, jobject /*object*/, jstring paramsString, jstring environmentString)
{
    m_mainLibraryHnd = NULL;
    const char *nativeString = env->GetStringUTFChars(environmentString, 0);
    QByteArray string = nativeString;
    env->ReleaseStringUTFChars(environmentString, nativeString);
    m_applicationParams=string.split('\t');
    foreach (string, m_applicationParams) {
        if (!string.isEmpty() && putenv(string.constData()))
            qWarning() << "Can't set environment" << string;
    }

    nativeString = env->GetStringUTFChars(paramsString, 0);
    string = nativeString;
    env->ReleaseStringUTFChars(paramsString, nativeString);

    m_applicationParams=string.split('\t');

    // Go home
    QDir::setCurrent(QDir::homePath());

    //look for main()
    if (m_applicationParams.length()) {
        // Obtain a handle to the main library (the library that contains the main() function).
        // This library should already be loaded, and calling dlopen() will just return a reference to it.
        m_mainLibraryHnd = dlopen(m_applicationParams.first().data(), 0);
        if (m_mainLibraryHnd == NULL) {
            qCritical() << "dlopen failed:" << dlerror();
            return false;
        }
        m_main = (Main)dlsym(m_mainLibraryHnd, "main");
    } else {
        qWarning() << "No main library was specified; searching entire process (this is slow!)";
        m_main = (Main)dlsym(RTLD_DEFAULT, "main");
    }

    if (!m_main) {
        qCritical() << "dlsym failed:" << dlerror();
        qCritical() << "Could not find main method";
        return false;
    }

    pthread_t appThread;
    return pthread_create(&appThread, NULL, startMainMethod, NULL) == 0;
}
Esempio n. 12
0
uint RedisClient::Response::getRedirectionPort() const
{
    if (!isMovedRedirect() && !isAskRedirect())
        return 0;

    QByteArray hostAndPort = m_responseSource.split(' ')[2];

    return QString(hostAndPort.split(':')[1]).toUInt();
}
Esempio n. 13
0
void CMakeValidator::parseFunctionOutput(const QByteArray &output)
{
    QList<QByteArray> cmakeFunctionsList = output.split('\n');
    m_functions.clear();
    if (!cmakeFunctionsList.isEmpty()) {
        cmakeFunctionsList.removeFirst(); //remove version string
        foreach (const QByteArray &function, cmakeFunctionsList)
            m_functions << QString::fromLocal8Bit(function.trimmed());
    }
Esempio n. 14
0
void FixProtocol::transform(const QByteArray &input, QByteArray &output)
{
    QList<QByteArray> fields = input.split(0x01);
    for (int i = 0; i < fields.size(); i++) {
        output.append(translateField(fields.at(i)));
        if (!output.isEmpty())
            output.append('\n');
    }
}
Esempio n. 15
0
void FindUtils::locate_process_finished()
{
    QByteArray output = locate_process->readAllStandardOutput().trimmed();
    QList<QByteArray> matches = output.split('\n');

    filter_results(matches);

    emit locate_finished(search_results);
}
Esempio n. 16
0
void THttpRequest::parseBody(const QByteArray &body, const THttpRequestHeader &header)
{
    switch (method()) {
    case Tf::Post: {
        QString ctype = QString::fromLatin1(header.contentType().trimmed());
        if (ctype.startsWith("multipart/form-data", Qt::CaseInsensitive)) {
            // multipart/form-data
            d->multipartFormData = TMultipartFormData(body, boundary());
            d->formItems = d->multipartFormData.formItems();

        } else if (ctype.startsWith("application/json", Qt::CaseInsensitive)) {
#if QT_VERSION >= 0x050000
            d->jsonData = QJsonDocument::fromJson(body);
#else
            tSystemWarn("unsupported content-type: %s", qPrintable(ctype));
#endif
        } else {
            // 'application/x-www-form-urlencoded'
            if (!body.isEmpty()) {
                QList<QByteArray> formdata = body.split('&');
                for (QListIterator<QByteArray> i(formdata); i.hasNext(); ) {
                    QList<QByteArray> nameval = i.next().split('=');
                    if (!nameval.value(0).isEmpty()) {
                        // URL decode
                        QString key = THttpUtility::fromUrlEncoding(nameval.value(0));
                        QString val = THttpUtility::fromUrlEncoding(nameval.value(1));
                        d->formItems.insertMulti(key, val);
                        tSystemDebug("POST Hash << %s : %s", qPrintable(key), qPrintable(val));
                    }
                }
            }
        }
        /* FALL THROUGH */ }

    case Tf::Get: {
        // query parameter
        QList<QByteArray> data = d->header.path().split('?');
        QString getdata = data.value(1);
        if (!getdata.isEmpty()) {
            QStringList pairs = getdata.split('&', QString::SkipEmptyParts);
            for (QStringListIterator i(pairs); i.hasNext(); ) {
                QStringList s = i.next().split('=');
                if (!s.value(0).isEmpty()) {
                    QString key = THttpUtility::fromUrlEncoding(s.value(0).toLatin1());
                    QString val = THttpUtility::fromUrlEncoding(s.value(1).toLatin1());
                    d->queryItems.insertMulti(key, val);
                    tSystemDebug("GET Hash << %s : %s", qPrintable(key), qPrintable(val));
                }
            }
        }
        break; }

    default:
        // do nothing
        break;
    }
}
Esempio n. 17
0
QByteArray RedisClient::Response::getRedirectionHost() const
{
    if (!isMovedRedirect() && !isAskRedirect())
        return QByteArray();

    QByteArray hostAndPort = m_responseSource.split(' ')[2];

    return hostAndPort.split(':')[0];
}
Esempio n. 18
0
qint64 ValgrindRunner::runMassif(const QString &qbsCommand, const QString &buildDir, bool dryRun,
                                  const QString &outFile)
{
    runProcess(valgrindCommandLine(qbsCommand, buildDir, dryRun, "massif", outFile));
    QByteArray ms_printOutput;
    runProcess(QStringList() << "ms_print" << outFile, QString(), &ms_printOutput);
    QBuffer buffer(&ms_printOutput);
    buffer.open(QIODevice::ReadOnly);
    QByteArray peakSnapshot;
    const QString exceptionStringPattern = QString::fromLatin1("Failed to extract peak memory "
            "usage from file '%1': %2").arg(outFile);
    while (!buffer.atEnd()) {
        const QByteArray line = buffer.readLine();
        static const QByteArray magicString = " (peak)";
        const int magicStringOffset = line.indexOf(magicString);
        if (magicStringOffset == -1)
            continue;
        int delimiterOffset = line.lastIndexOf(',', magicStringOffset);
        if (delimiterOffset == -1)
            delimiterOffset = line.lastIndexOf('[', magicStringOffset);
        if (delimiterOffset == -1) {
            const QString details = QString::fromLatin1("Failed to extract peak snapshot from "
                    "line '%1'.").arg(QString::fromLocal8Bit(line));
            throw Exception(exceptionStringPattern.arg(details));
        }
        peakSnapshot = line.mid(delimiterOffset + 1, magicStringOffset - delimiterOffset).trimmed();
        break;
    }
    if (peakSnapshot.isEmpty())
        throw Exception(exceptionStringPattern.arg("No peak marker found"));
    while (!buffer.atEnd()) {
        const QByteArray line = buffer.readLine().simplified();
        if (!line.startsWith(peakSnapshot + ' '))
            continue;
        const QList<QByteArray> entries = line.split(' ');
        if (entries.size() != 6) {
            const QString details = QString::fromLatin1("Expected 6 entries in line '%1', but "
                    "there are %2.").arg(QString::fromLocal8Bit(line)).arg(entries.size());
            throw Exception(exceptionStringPattern.arg(details));
        }
        QByteArray peakMemoryString = entries.at(2);
        peakMemoryString.replace(',', QByteArray());
        bool ok;
        qint64 peakMemoryUsage = peakMemoryString.toLongLong(&ok);
        if (!ok) {
            const QString details = QString::fromLatin1("Failed to parse peak memory value '%1' "
                    "as a number.").arg(QString::fromLocal8Bit(peakMemoryString));
            throw Exception(exceptionStringPattern.arg(details));
        }
        return peakMemoryUsage;
    }

    const QString details = QString::fromLatin1("Failed to find snapshot '%1'.")
            .arg(QString::fromLocal8Bit(peakSnapshot));
    throw Exception(exceptionStringPattern.arg(details));
}
 void getTitleOutput(int exitCode)
 {
     if (exitCode == 0) {
         QByteArray out = titleProcess.readAllStandardOutput();
         QList<QByteArray> outputList = out.split('\n');
         qDebug() << "Called the C++ slot and got following url:" << outputList[0];
         streamTitle = outputList[0];
         sTitleChanged(streamTitle);
     }
 }
Esempio n. 20
0
static QMap<char, QByteArray> parseGS2(const QByteArray &ba)
{
    QMap<char, QByteArray> map;
    foreach (const QByteArray &keyValue, ba.split(',')) {
        if (keyValue.size() >= 2 && keyValue[1] == '=') {
            map[keyValue[0]] = keyValue.mid(2);
        }
    }
    return map;
}
Esempio n. 21
0
bool StreamNegotiation::parse(QByteArray decodedResponse)
{
    QList<QByteArray> m_clientFirstResponseMapList = decodedResponse.split(',');

    foreach (QByteArray data, m_clientFirstResponseMapList)
    {
        QString key = QString(data.left(data.indexOf('=')));
        QByteArray value = data.mid(data.indexOf('=') + 1).replace(QByteArray("\""), QByteArray(""));
        m_map.insert(key, value);
    }
Esempio n. 22
0
/*!
    Parses the cookie string \a cookieString as received from a server
    response in the "Set-Cookie:" header. If there's a parsing error,
    this function returns an empty list.

    Since the HTTP header can set more than one cookie at the same
    time, this function returns a QList<QNetworkCookie>, one for each
    cookie that is parsed.

    \sa toRawForm()
*/
QList<QNetworkCookie> QNetworkCookie::parseCookies(const QByteArray &cookieString)
{
    // cookieString can be a number of set-cookie header strings joined together
    // by \n, parse each line separately.
    QList<QNetworkCookie> cookies;
    QList<QByteArray> list = cookieString.split('\n');
    for (int a = 0; a < list.size(); a++)
        cookies += QNetworkCookiePrivate::parseSetCookieHeaderLine(list.at(a));
    return cookies;
}
Esempio n. 23
0
void VpncUiPluginPrivate::gotCiscoDecryptOutput()
{
    QByteArray output = ciscoDecrypt->readAll();
    if (!output.isEmpty()) {
        QList<QByteArray> lines = output.split('\n');
        if (!lines.isEmpty()) {
            decryptedPasswd = QString::fromUtf8(lines.first());
        }
    }
}
Esempio n. 24
0
QStringList byteArrayToStringList(const QByteArray& r) {
    QStringList items;
    foreach ( const QByteArray& item, r.split('\n') ) {
        items << item.data();
    }
    if ( r.endsWith('\n') ) {
        items.pop_back();
    }
    return items;
}
Esempio n. 25
0
void TcfEngine::handleResponse(const QByteArray &response)
{
    static QTime lastTime;

    //emit tcfOutputAvailable(_("            "), currentTime());
    QList<QByteArray> parts = response.split('\0');
    if (parts.size() < 2 || !parts.last().isEmpty()) {
        SDEBUG("WRONG RESPONSE PACKET LAYOUT" << parts);
        //if (response.isEmpty())
            acknowledgeResult();
        return;
    }
    parts.removeLast(); // always empty
    QByteArray tag = parts.at(0);
    int n = parts.size();
    if (n == 2 && tag == "N") { // unidentified command
        int token = parts.at(1).toInt();
        TcfCommand tcf = m_cookieForToken[token];
        SDEBUG("COMMAND NOT RECOGNIZED FOR TOKEN" << token << tcf.toString());
        emit tcfOutputAvailable(LogOutput, QString::number(token) + "^"
               + "NOT RECOQNIZED: " + quoteUnprintableLatin1(response));
        acknowledgeResult();
    } else if (n == 2 && tag == "F") { // flow control
        m_congestion = parts.at(1).toInt();
        SDEBUG("CONGESTION: " << m_congestion);
    } else if (n == 4 && tag == "R") { // result data
        acknowledgeResult();
        int token = parts.at(1).toInt();
        QByteArray message = parts.at(2);
        JsonValue data(parts.at(3));
        emit tcfOutputAvailable(LogOutput, QString("%1^%2%3").arg(token)
            .arg(quoteUnprintableLatin1(response))
            .arg(QString::fromUtf8(data.toString())));
        TcfCommand tcf = m_cookieForToken[token];
        JsonValue result(data);
        SDEBUG("GOOD RESPONSE: " << quoteUnprintableLatin1(response));
        if (tcf.callback)
            (this->*(tcf.callback))(result, tcf.cookie);
    } else if (n == 3 && tag == "P") { // progress data (partial result)
        //int token = parts.at(1).toInt();
        QByteArray data = parts.at(2);
        SDEBUG(_("\nTCF PARTIAL:") << quoteUnprintableLatin1(response));
    } else if (n == 4 && tag == "E") { // an event
        QByteArray service = parts.at(1);
        QByteArray eventName = parts.at(2);
        JsonValue data(parts.at(3));
        if (eventName != "peerHeartBeat")
            SDEBUG(_("\nTCF EVENT:") << quoteUnprintableLatin1(response)
                << data.toString());
        if (service == "Locator" && eventName == "Hello") {
            m_services.clear();
            foreach (const JsonValue &service, data.children())
                m_services.append(service.data());
            QTimer::singleShot(0, this, SLOT(startDebugging()));
        }
Esempio n. 26
0
/*
tokens:
0 = timestamp
1 = Transmission direction
2 = ID
3 = Data byte length
4-x = The data bytes
*/
bool FrameFileIO::loadMicrochipFile(QString filename, QVector<CANFrame>* frames)
{
    QFile *inFile = new QFile(filename);
    CANFrame thisFrame;
    QByteArray line;
    bool inComment = false;
    long long timeStamp = Utility::GetTimeMS();
    int lineCounter = 0;

    if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        delete inFile;
        return false;
    }

    //line = inFile->readLine(); //read out the header first and discard it.

    while (!inFile->atEnd()) {
        lineCounter++;
        if (lineCounter > 100)
        {
            qApp->processEvents();
            lineCounter = 0;
        }

        line = inFile->readLine();
        if (line.length() > 2)
        {
            if (line.startsWith("//"))
            {
                inComment = !inComment;
            }
            else
            {
                if (!inComment)
                {
                    QList<QByteArray> tokens = line.split(';');
                    timeStamp += 5;
                    thisFrame.timestamp = timeStamp;

                    thisFrame.ID = Utility::ParseStringToNum(tokens[2]);
                    if (thisFrame.ID <= 0x7FF) thisFrame.extended = false;
                    else thisFrame.extended = true;
                    thisFrame.bus = 0;
                    thisFrame.len = tokens[3].toInt();
                    for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)Utility::ParseStringToNum(tokens[4 + d]);
                    frames->append(thisFrame);
                }
            }
        }
    }
    inFile->close();
    delete inFile;
    return true;
}
Esempio n. 27
0
void client::readMessage()
{
	QByteArray message = socket->readAll();

	qDebug() << "reading...";
	//qDebug() << message;

	QList<QByteArray> message_list= message.split('\n');
	qDebug() << message_list;

	QJsonDocument json_document;
	QJsonObject json_object;
	QJsonValue type;
	for (int i=0; i<message_list.size(); i++){
		json_document = QJsonDocument::fromJson(message_list.at(i));
		json_object = json_document.object();
		type = json_object.value("type");

		if (type == "login"){
			player_id = json_object.value("id").toInt();
			emit on_login();
		} else if (type == "response"){
			if (json_object.value("object") == "rooms"){
				rooms = json_object.value("data").toArray();
				emit on_refresh_rooms(rooms);
			} else if (json_object.value("object") == "players"){
				players = json_object.value("data").toArray();
				emit on_refresh_players(players);
			} else if (json_object.value("object") == "board"){
				board = json_object.value("data").toArray();
				emit on_refresh_board(board);
			}
		} else if (type == "newroom"){
			emit on_create_room(json_object.value("rid").toInt());
		} else if (type == "join"){
			emit on_join(json_object.value("rid").toInt());
		} else if (type == "closegame") {
			emit on_close_game();
		} else if (type == "startgame") {
			emit on_start_game();
		} else if (type == "play") {
			emit on_update_game(json_object);
		} else if (type == "win") {
			emit on_game_over(json_object);
		} else if (type == "highlight") {
			emit on_highlight(json_object);
		} else if (type == "chat") {
			emit on_chat(json_object);
		} else if (type == "spectate") {
			emit on_spectate(json_object.value("rid").toInt());
		}
	}


}
Esempio n. 28
0
// used by mapplauncherd to bring a binary to the front
void WindowModel::launchProcess(const QString &binaryName)
{
    LipstickCompositor *c = LipstickCompositor::instance();
    if (!m_complete || !c)
        return;

    QStringList binaryParts = binaryName.split(QRegExp(QRegExp("\\s+")));

    for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin();
        iter != c->m_mappedSurfaces.end(); ++iter) {

        LipstickCompositorWindow *win = iter.value();
        if (!approveWindow(win))
            continue;

        QString pidFile = QString::fromLatin1("/proc/%1/cmdline").arg(win->processId());
        QFile f(pidFile);
        if (!f.open(QIODevice::ReadOnly)) {
            qWarning() << Q_FUNC_INFO << "Cannot open cmdline for " << pidFile;
            continue;
        }

        // Command line arguments are split by '\0' in /proc/*/cmdline
        QStringList proc;
        QByteArray data = f.readAll();
        Q_FOREACH (const QByteArray &array, data.split('\0')) {
            QString part = QString::fromUtf8(array);
            if (part.size() > 0) {
                proc << part;
            }
        }

        // Cannot match, as the cmdline has less arguments than then binary part
        if (binaryParts.size() > proc.size()) {
            continue;
        }

        bool match = true;

        // All parts of binaryName must be contained in this order in the
        // process command line to match the given process
        for (int i=0; i<binaryParts.count(); i++) {
            if (proc[i] != binaryParts[i]) {
                match = false;
                break;
            }
        }

        if (match) {
            win->surface()->raiseRequested();
            break;
        }
    }
}
Esempio n. 29
0
 QList<Utils::Port> usedPorts(const QByteArray &output) const override
 {
     QList<Utils::Port> ports;
     const QList<QByteArray> lines = output.split('\n');
     for (const QByteArray &line : lines) {
         const Port port(Utils::parseUsedPortFromNetstatOutput(line));
         if (port.isValid() && !ports.contains(port))
             ports.append(port);
     }
     return ports;
 }
Esempio n. 30
0
void CLbsPositionLogger::readNextPosition()
{
    QByteArray line = m_logFile.readLine().trimmed();
    if (line.isEmpty()) {
        LOG_MODEL_ERROR("CLbsPositionLogger", "no readlien");
        return;
    }
    
    QList<QByteArray> data = line.split(',');
    
    QGeoCoordinate coordinate;
    QGeoPositionInfo info;
    
    bool hasTimestamp = false;
    QDateTime timestamp = QDateTime::fromTime_t(data.value(0).toLong(&hasTimestamp), Qt::UTC);
    if(hasTimestamp && timestamp.isValid())
        info.setTimestamp(timestamp);
    double latitude;
    bool hasLatitude = false;
    latitude = data.value(1).toDouble(&hasLatitude);
    if(hasLatitude)
        coordinate.setLatitude(latitude);
    double longitude;
    bool hasLongitude = false;
    longitude = data.value(2).toDouble(&hasLongitude);
    if(hasLongitude)
        coordinate.setLongitude(longitude);
    double altitude;
    bool hasAltitude = false;
    altitude = data.value(3).toDouble(&hasAltitude);
    if(hasAltitude)
        coordinate.setAltitude(altitude);
    info.setCoordinate(coordinate);
    
    double HorizontalAccuracy;
    bool hasHorizontalAccuracy = false;
    HorizontalAccuracy = data.value(4).toDouble(&hasHorizontalAccuracy);
    if(hasHorizontalAccuracy)
        info.setAttribute(QGeoPositionInfo::HorizontalAccuracy, HorizontalAccuracy);
    double Direction;
    bool hasDirection = false;
    Direction = data.value(5).toDouble(&hasDirection);
    if(hasDirection)
        info.setAttribute(QGeoPositionInfo::Direction, Direction);
    double GroundSpeed;
    bool hasGroundSpeed = false;
    GroundSpeed = data.value(6).toDouble(&hasGroundSpeed);
    if(hasGroundSpeed)
        info.setAttribute(QGeoPositionInfo::GroundSpeed, GroundSpeed);
    if (info.isValid()) {
        m_lastPosition = info;
        emit positionUpdated(info);
    }
}