Example #1
0
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);
}
static void parseSharedLibs(const QByteArray &buffer, QStringList *libs)
{
#if defined(_WIN32)
    QList<QByteArray> lines = buffer.trimmed().split('\r');
#else
    QList<QByteArray> lines = buffer.trimmed().split('\n');
#endif
    foreach (const QByteArray &line, lines) {
        if (line.contains("(NEEDED)") && line.contains("Shared library:") ) {
            const int pos = line.lastIndexOf('[') + 1;
            (*libs) << QString::fromLatin1(line.mid(pos, line.length() - pos - 1));
        }
    }
}
Example #3
0
void Oinv_cgrid::set_transparency( const QString& str ) {
  for( int i = 0; i < 256; i++ ) {
    volrend_colormap_->colorMap.set1Value( 4*i+3, 1.0f );
  }

  if( !cmap_ || str.isEmpty() ) return;
  
  float min = cmap_->lower_bound();
  float max = cmap_->upper_bound();
  if( min == max ) return;

  QString cleaned_intervals;
  const float alpha = 0.01f;
//  volrend_colormap_->colorMap.set1Value( 3, alpha );
//  volrend_colormap_->colorMap.set1Value( 7, alpha );

  QStringList intervals_str = str.split( ";", QString::SkipEmptyParts);
  QStringList::Iterator it = intervals_str.begin(); 
  for ( ; it != intervals_str.end(); ++it ) {
    QStringList interval_str = (*it).split( ",",QString::SkipEmptyParts);
    if( interval_str.size() != 2 ) continue; 

    cleaned_intervals += interval_str[0] + " , " + interval_str[1] + " ; ";

    QByteArray tmp = interval_str[0].toLatin1();
    float low = std::max( tmp.trimmed().toFloat(), min );
    tmp = interval_str[1].toLatin1();
    float high= std::min( tmp.trimmed().toFloat(), max );
    
    int a= (low  - min) / ( max - min ) * 255;
    int b= (high - min) / ( max - min ) * 255;

    appli_assert( a >=0 && b < 256 );
    for( int i = a; i <= b; i++ ) {
      volrend_colormap_->colorMap.set1Value( 4*i+3, alpha );
    }
  }

  std::map< std::string, QString >::iterator found = 
    transparency_map_.find( current_property_name_ );
  if( found == transparency_map_.end() )
    transparency_map_.insert( 
      std::make_pair( current_property_name_, cleaned_intervals) 
     );
  else {
    found->second = cleaned_intervals;
  }
}
Example #4
0
static void readQuality(U2OpStatus& os, IOAdapter *io, QByteArray &sequence, int count) {

    QByteArray buffArray(DocumentFormat::READ_BUFF_SIZE + 1, 0);
    char* buff = buffArray.data();

    // reading quality sequence, ignoring whitespace at the beginning and the end of lines

    int readed = 0;
    while (!io->isEof() && (readed < count)) {
        bool eolnFound = false;
        int readedCount = io->readUntil(buff, DocumentFormat::READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &eolnFound);
        CHECK_EXT(readedCount >= 0, os.setError(U2::FastqFormat::tr("Error while reading sequence")),);

        QByteArray trimmed = QByteArray(buffArray.data(), readedCount);
        trimmed = trimmed.trimmed();

        int qualitySize = sequence.size() + trimmed.size();
        if (eolnFound && (qualitySize > count)) { // read quality sequence name line, reverting back
            io->skip(-readedCount);
            return;
        }

        sequence.append(trimmed);
        CHECK_OP(os,);
    }
}
Example #5
0
void HttpLabel::networkReplyFinished(QNetworkReply * reply)
{
    QByteArray data = reply->readAll();
    qDebug() << "HttpLabel::networkReplyFinished" << data.trimmed();
    setText(d->pattern.arg(((QString)data).trimmed()));
    d->timer.start(d->interval, this);
}
Example #6
0
void UCHome_Main_SiteConst::clean_my_name_lable()
{
    //<my:name uid="1673222" />
    //<my:name uid="1673222"></my:name>

    //QString unis = this->codec->toUnicode(this->feed_page_html);
    //QByteArray u8s = this->u8codec->fromUnicode(unis);
    //unis = u8s;
    QByteArray tarr = this->feed_page_html;

    QRegExp exp1 ("<my:name uid=\"[0-9]{1,12}\" />");
    QRegExp exp2 ( "<my:name uid=\"[0-9]{1,12}\"></my:name>");
    
    tarr = tarr.trimmed();
    if(tarr.startsWith("f5b")) {
        tarr = tarr.right(tarr.length()-3);
    }
    if(tarr.endsWith("0")) {
        tarr = tarr.left(tarr.length()-1);
    }
    //unis = unis.replace(exp1, QString(""));
    //unis = unis.replace(exp2, QString(""));
    
    //u8s = this->u8codec->fromUnicode(unis);
    QString unis = this->codec->toUnicode(tarr);

    this->feed_page_utf8_html = this->u8codec->fromUnicode(unis);

    this->feed_page_utf8_html = this->u8codec->fromUnicode(this->codec->toUnicode(this->feed_page_html));
}
Example #7
0
//当客户端发送消息时触发的槽函数
void MainWindow::Ser_dataReceive()
{
    //用于保存消息的临时对象
    QByteArray message;
    //从tcpSocket获取消息
    message=tcpSocket->readAll();
    //向infopad追加状态信息
    ui->infoPad->append(tcpSocket->peerAddress().toString()+":");
    //向infopad追加状态信息
    ui->infoPad->append("\t"+message);
    //在这里可以完成规则检查或协议解析过程
    //目前并没有考虑协议优化等
    //目前使用的不是一个较好的协议,而是字符串协议
    //以下为命令解析的过程,解析成功返回SUCCESS,失败返回FAIL
    if( Ser_cmd_parser(message.trimmed())==Utils::SUCCESS)
    {
        //调试信息
        qDebug()<<"SER:parser ok";
    }
    else
    {
        //调试信息
        qDebug()<<"SER:parser fail";
    }
    //send back message or something other
    //调试信息
    //tcpSocket->write(message);
    //调试信息
     qDebug()<<"Ser:server receive ok";
}
Example #8
0
/**
 * @brief  Create an AWS V3 Signature canonical header string.
 *
 * @note   Amazon documentation does not specify how to handle whitespace within
 *         quotes for V3 signatures, so here we use the same approach as V3
 *         signatures.  That is:
 *
 * In canonical form, header name and value are combined with a single semi-colon
 * separator, with all whitespace removed from both, _except_ for whitespace within
 * double-quotes.
 *
 * @note   This function is only applicable to the `AWS3` format, not `AWS3-HTTPS`.
 *
 * @param  headerName   Name of the HTTP header to convert to canonical form.
 * @param  headerValue  Value of the HTTP header to convert to canonical form.
 *
 * @return  An AWS V3 Signature canonical header string.
 *
 * @see    http://docs.aws.amazon.com/amazonswf/latest/developerguide/HMACAuth-swf.html
 * @see    http://docs.aws.amazon.com/general/latest/gr/sigV4-create-canonical-request.html
 * @see    canonicalHeaders
 */
QByteArray AwsSignatureV3Private::canonicalHeader(const QByteArray &headerName, const QByteArray &headerValue) const
{
    QByteArray header = headerName.toLower() + ':';
    const QByteArray trimmedHeaderValue = headerValue.trimmed();
    bool isInQuotes = false;
    char previousChar = '\0';
    for (int index = 0; index < trimmedHeaderValue.size(); ++index) {
        char thisChar = trimmedHeaderValue.at(index);
        header += thisChar;
        if (isInQuotes) {
            if ((thisChar == '"') && (previousChar != '\\'))
                isInQuotes = false;
        } else {
            if ((thisChar == '"') && (previousChar != '\\')) {
                isInQuotes = true;
            } else if (isspace(thisChar)) {
                while ((index < trimmedHeaderValue.size()-1) &&
                       (isspace(trimmedHeaderValue.at(index+1))))
                    ++index;
            }
        }
        previousChar = thisChar;
    }
    return header;
}
Example #9
0
void tst_QUdpSocket::outOfProcessUnconnectedClientServerTest()
{
#if defined(Q_OS_WINCE)
    QSKIP("This test depends on reading data from QProcess (not supported on Qt/WinCE.", SkipAll);
#endif
#if defined(QT_NO_PROCESS)
    QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
#else

    QProcess serverProcess;
    serverProcess.start(QLatin1String("clientserver/clientserver server 1 1"),
                        QIODevice::ReadWrite | QIODevice::Text);

    // Wait until the server has started and reports success.
    while (!serverProcess.canReadLine())
        QVERIFY(serverProcess.waitForReadyRead(3000));
    QByteArray serverGreeting = serverProcess.readLine();
    QVERIFY(serverGreeting != QByteArray("XXX\n"));
    int serverPort = serverGreeting.trimmed().toInt();
    QVERIFY(serverPort > 0 && serverPort < 65536);

    QProcess clientProcess;
    clientProcess.start(QString::fromLatin1("clientserver/clientserver unconnectedclient %1 %2")
                        .arg(QLatin1String("127.0.0.1")).arg(serverPort),
                        QIODevice::ReadWrite | QIODevice::Text);
    // Wait until the server has started and reports success.
    while (!clientProcess.canReadLine())
        QVERIFY(clientProcess.waitForReadyRead(3000));
    QByteArray clientGreeting = clientProcess.readLine();
    QCOMPARE(clientGreeting, QByteArray("ok\n"));

    // Let the client and server talk for 3 seconds
    QTest::qWait(3000);

    QStringList serverData = QString::fromLocal8Bit(serverProcess.readAll()).split("\n");
    QStringList clientData = QString::fromLocal8Bit(clientProcess.readAll()).split("\n");

    QVERIFY(serverData.size() > 5);
    QVERIFY(clientData.size() > 5);

    for (int i = 0; i < clientData.size() / 2; ++i) {
        QCOMPARE(clientData.at(i * 2), QString("readData()"));
        QCOMPARE(serverData.at(i * 3), QString("readData()"));

        QString cdata = clientData.at(i * 2 + 1);
        QString sdata = serverData.at(i * 3 + 1);
        QVERIFY(cdata.startsWith(QLatin1String("got ")));

        QCOMPARE(cdata.mid(4).trimmed().toInt(), sdata.mid(4).trimmed().toInt() * 2);
        QVERIFY(serverData.at(i * 3 + 2).startsWith(QLatin1String("sending ")));
        QCOMPARE(serverData.at(i * 3 + 2).trimmed().mid(8).toInt(),
                 sdata.mid(4).trimmed().toInt() * 2);
    }

    clientProcess.kill();
    QVERIFY(clientProcess.waitForFinished());
    serverProcess.kill();
    QVERIFY(serverProcess.waitForFinished());
#endif
}
Example #10
0
static void readSequence(U2OpStatus& os, IOAdapter *io, QByteArray &sequence, char readUntil = '+') {

    QByteArray buffArray(DocumentFormat::READ_BUFF_SIZE + 1, 0);
    char* buff = buffArray.data();

    // reading until readUntil symbol i.e. quality or dna sequence name start, ignoring whitespace at the beginning and the end of lines

    while (!io->isEof()) {
        bool eolnFound = false;
        int readedCount = io->readUntil(buff, DocumentFormat::READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &eolnFound);
        CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );
        CHECK_EXT(readedCount >= 0, os.setError(U2::FastqFormat::tr("Error while reading sequence")),);

        QByteArray trimmed = QByteArray(buffArray.data(), readedCount);
        trimmed = trimmed.trimmed();

        if (eolnFound && checkFirstSymbol(trimmed, readUntil)) { // read quality sequence name line, reverting back
            io->skip(-readedCount);
            if (io->hasError()) {
                os.setError(io->errorString());
            }
            return;
        }

        sequence.append(trimmed);
        CHECK_OP(os,);
    }
    if (io->hasError()) {
        os.setError(io->errorString());
    }
}
Example #11
0
int SqlQuery::prepare(const QByteArray &sql, bool allow_failure)
{
    _sql = sql.trimmed();
    if (_stmt) {
        finish();
    }
    if (!_sql.isEmpty()) {
        int n = 0;
        int rc;
        do {
            rc = sqlite3_prepare_v2(_db, _sql.constData(), -1, &_stmt, 0);
            if ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)) {
                n++;
                OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
            }
        } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
        _errId = rc;

        if (_errId != SQLITE_OK) {
            _error = QString::fromUtf8(sqlite3_errmsg(_db));
            qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" << _sql;
            ENFORCE(allow_failure, "SQLITE Prepare error");
        } else {
            ASSERT(_stmt);
            _sqldb->_queries.insert(this);
        }
    }
    return _errId;
}
Example #12
0
  QString ddMainWindow::getEnvPath(int type)
  {
      QString env = "";

      switch (type)
      {
        case eSDCARD: env = "$EXTERNAL_STORAGE";
          break;
        case eDATA: env = "$ANDROID_DATA";
          break;

      case eSDCARD_EXT: env = "$EXTERNAL_STORAGE2";
        break;


      }


      QProcess proc;
      QString cmd = "adb";
      QStringList argAdb;
      argAdb << "shell" << "echo" << env ;
      proc.start(cmd, argAdb);
      qDebug() <<  " pid =" << proc.pid() << " process started"  ;
      if (!proc.waitForFinished())
          return false;

      QByteArray res = proc.readLine();

      return res.trimmed();

  }
Example #13
0
void AsteriskManager::onReadyRead()
{
	QRegExp keyValue("^([A-Za-z0-9\\-]+):\\s(.+)$");
	QByteArray line;

    qDebug("<ami>");

	while (canReadLine()) {
		line = readLine();

        qDebug() << line.trimmed();

		if (line != "\r\n") {
            if (keyValue.indexIn(line) > -1) {
				packetBuffer[keyValue.cap(1)] = stringValue(keyValue.cap(2).trimmed());
            } else if (line.startsWith("Asterisk Call Manager")) {
                version_ = line.replace("Asterisk Call Manager/", QByteArray()).trimmed();

                emit connected(version_);
            }
		} else if (!packetBuffer.isEmpty()) {
			dispatchPacket();
		}
	}

    qDebug("</ami>");
}
Example #14
0
bool mdtCsvFile::readLines(QByteArray separator, QByteArray dataProtection, QByteArray comment)
{
  Q_ASSERT(separator != dataProtection);
  Q_ASSERT(separator != comment);
  Q_ASSERT(dataProtection != comment);

  QByteArray line;

  // Check if file was open
  if(!isOpen()){
    setErrorString(tr("mdtCsvFile::readLines(): file is not open"));
    return false;
  }
  // Clear previous results
  clear();
  // Travel the file
  while(!atEnd()){
    // Read a line
    line = readLine();
    // Remove begin and end whit space, end of line, etc...
    line = line.trimmed();
    if(line.size() > 0){
      // Check about comments
      if((comment.size() > 0)&&(line.startsWith(comment))){
        continue;
      }
      // Parse the block
      pvLines << parseLine(line, separator, dataProtection);
    }
  }

  return true;
}
Example #15
0
void BcRequest::onProcessFinished()
{
	qDebug() << "BC: Process finished";
	QByteArray out;
	if (proc_->bytesAvailable() > 1024 ) {
		plugin()->reply(stanza(), "sorry, result is too long");
		deleteLater();
		return;
	}
	out.append( proc_->readAllStandardOutput() );
	out.append( proc_->readAllStandardError() );
	QString msg(out.trimmed());
	int i = msg.length();

	if (i <= 0 ) {
		deleteLater();
		return;
	}
	if (msg.indexOf('.') != -1) {
		while (i--) {
			if (msg.at(i) != '0') break;
		}
		if (msg.at(i) != '.') i++;
	}

	plugin()->reply( stanza(), QString(msg.left(i).toUtf8()).trimmed());
	deleteLater();
}
qreal MStyleSheetAttribute::attributeToFloat(const QByteArray &attribute, bool *conversionOk)
{
    QByteArray value = attribute.trimmed();

    if (attribute.endsWith(units[PIXELS_UNIT])) {
        // strip "px" from the end
        value.truncate(value.length() - 2);
        return value.toFloat(conversionOk);
    }

    if (attribute.endsWith(units[MM_UNIT])) {
        // strip "mm" from the end
        value.truncate(value.length() - 2);

        return MDeviceProfile::instance()->mmToPixelsF(value.toFloat(conversionOk));
    }

    if (attribute.endsWith(units[PT_UNIT])) {
        // strip "pt" from the end
        value.truncate(value.length() - 2);

        return MDeviceProfile::instance()->ptToPixelsF(value.toFloat(conversionOk));
    }

    return value.toFloat(conversionOk);
}
Example #17
0
void Asterisk::onSocketReadyRead()
{
//    qDebug("<ready-read>");

    QVariantHash headers;

    while (socket.canReadLine()) {
        QByteArray line = socket.readLine();

//        qDebug() << "Line:" << line;

        if (line != "\r\n") {
            QStringList header = QString(line.trimmed()).split(':');

            headers.insertMulti(header[0], decodeValue(header[1].trimmed()));
        } else {
            if (headers.contains("Response"))
                responses.insert(headers.take("ActionID").toString(), headers);
            else if (headers.contains("Event"))
                emit eventReceived(headers.take("Event").toString(), headers);

            headers.clear();
        }
    }

//    qDebug("</ready-read>");
}
Example #18
0
QVariantHash FSTReader::parseMapping(QIODevice* device) {
    QVariantHash properties;
    
    QByteArray line;
    while (!(line = device->readLine()).isEmpty()) {
        if ((line = line.trimmed()).startsWith('#')) {
            continue; // comment
        }
        QList<QByteArray> sections = line.split('=');
        if (sections.size() < 2) {
            continue;
        }
        QByteArray name = sections.at(0).trimmed();
        if (sections.size() == 2) {
            properties.insertMulti(name, sections.at(1).trimmed());
            
        } else if (sections.size() == 3) {
            QVariantHash heading = properties.value(name).toHash();
            heading.insertMulti(sections.at(1).trimmed(), sections.at(2).trimmed());
            properties.insert(name, heading);
            
        } else if (sections.size() >= 4) {
            QVariantHash heading = properties.value(name).toHash();
            QVariantList contents;
            for (int i = 2; i < sections.size(); i++) {
                contents.append(sections.at(i).trimmed());
            }
            heading.insertMulti(sections.at(1).trimmed(), contents);
            properties.insert(name, heading);
        }
    }
    
    return properties;
}
void RawTextGui::ExecuteFile()
{
    bool ok;
    uint i=0;
    QByteArray ascii_hex_val;
    QByteArray response;
    QByteArray byte;
    QList<QByteArray> byte_list;
    QString qmsg_start ="Exec: ASCII Script...";
    QString qmsg_success = "Exec: ASCII Script...Success!";
    QString str = "%1 | raw bytes text: %2 tx: %3 rx: %4";
    QString qmsg;
    uint d;

    QFile file(raw_file->text());

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QCoreApplication::sendEvent(parent->parent, new BPStatusMsgEvent(qmsg_start));

    ascii_hex_val = file.readAll().trimmed();
    byte_list = ascii_hex_val.replace('\n', ' ').split(' ');

    while(!byte_list.isEmpty())
    {
        byte = byte_list.takeFirst();
        d = byte.trimmed().toUShort(&ok, 0);
        response = parent->bp->command(d);
        qmsg = str.arg(i++, 3, 10, QChar('0')).arg(byte.data())
               .arg(d, 3, 10, QChar('0')).arg(response.toHex().data());
        QCoreApplication::sendEvent(this, new AsciiHexLogMsgEvent(qmsg));
    }
    QCoreApplication::sendEvent(parent->parent, new BPStatusMsgEvent(qmsg_success));
}
Example #20
0
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;
}
Example #21
0
ImapMailbox *ImapPrivate::parseMessages (ImapMailbox *mailbox) {
    QByteArray response;

    while (true) {
        // Read Message
        response.clear();       
        do {
            if (response.size() > 0) {
                response.remove(response.lastIndexOf('}'), 
                                response.size() - response.lastIndexOf('{'));
            }
            response.append(readLine());
        } while (isMultiline(response));

        // Break if End Response Found.
        if (isResponseEnd(response))
            break;

        // Parse and Add Message to Mailbox
        ImapMessage *message = _imapParseMessage(response.trimmed());
        if (message != NULL) mailbox->addMessage(message);
    }
    
    return(mailbox);
}
static void readLine( IOAdapter* io, QByteArray& to, QStringList* tokens = NULL ) {
    assert( NULL != io );
    to.clear();
    QByteArray buf( BUF_SZ, TERM_SYM );
    bool there = false;
    int bytes = 0;
    while( !there ) {
        int ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &there );
        if( 0 > ret ) {
            throw QString( "read_error_occurred" );
        }
        if( 0 == ret ) {
            break;
        }
        to.append( QByteArray( buf.data(), ret ) );
        bytes += ret;
    }
    to = to.trimmed();
    if( 0 == bytes ) {
        throw QString( "unexpected_end_of_file_found" );
    }

    if( NULL != tokens ) {
        *tokens = QString( to ).split( QRegExp( "\\s+" ), QString::SkipEmptyParts );
    }
}
Example #23
0
void
ScrobSocket::onReadyRead()
{
    QByteArray bytes = readAll();
    if (bytes != "OK\n") qWarning() << bytes.trimmed();
    disconnectFromHost();
}
void ServerCliant::ExecuteCommand(QByteArray ClientCommand)
{
    try
    {
        QByteArray Command = "";
        QByteArray Arg = "";

        if(ClientCommand.contains(" "))
        {
            //Contains arquments
            int pos = ClientCommand.indexOf(" ");
            Command = ClientCommand.mid(0,pos).trimmed();
            Arg = ClientCommand.mid(pos + 1);
        }
        else
        {
            //No arquments
            Command = ClientCommand.trimmed();
        }

        qDebug() << "ServerReplay: " << Command << " " << Arg<<"\n";


        if(Command=="INIT")
        {
            DoINIT(Arg.trimmed());

        }
        else if(Command=="DOWNSTART")
        {
            DoNewDownload(Arg);
        }





    }
    catch(QString err)
    {
        //SendResponse(550,err);
    }
    catch(...)
    {
        //SendResponse(550,"Unknown error in ExecuteCommand()");
    }
}
Example #25
0
UsbIds::UsbIds(QObject *parent):
    QObject(parent)
{
    QFile file(":/libuvc/share/usbdb/usb.ids");

    file.open(QIODevice::ReadOnly);
    QByteArray line;
    bool end = false;

    while (!end && !file.atEnd()) {
        line = file.readLine().trimmed();

        if (line.startsWith('#') || line.isEmpty())
            continue;

        auto start = line.indexOf(' ');
        auto vendorId = quint16(line.mid(0, start).toUInt(Q_NULLPTR, 16));
        auto vendor = line.mid(start).trimmed();
        QMap<quint16, QString> products;

        while (!file.atEnd()) {
            auto pos = file.pos();
            line = file.readLine();

            if (!line.startsWith('\t')) {
                if (line.trimmed().isEmpty())
                    end = true;

                file.seek(pos);

                break;
            }

            line = line.trimmed();
            auto start = line.indexOf(' ');
            auto productId = quint16(line.mid(0, start).toUInt(Q_NULLPTR, 16));
            auto product = line.mid(start).trimmed();
            products[productId] = product;
        }

        this->m_ids << UsbIdsElement {vendorId, vendor, products};
    }

    file.close();
}
Example #26
0
void TorControlSocket::sendCommand(TorControlCommand *command, const QByteArray &data)
{
    commandQueue.append(command);

    Q_ASSERT(data.endsWith("\r\n"));
    write(data);

    qDebug() << "torctrl: Sent" << data.trimmed();
}
bool DiagnosticsDialog::isPCSCRunning()
{
#ifdef Q_OS_LINUX
	QByteArray result = runProcess( "pidof", QStringList() << "pcscd" );
#else
	QByteArray result = runProcess( "sh -c \"ps ax | grep -v grep | grep pcscd\"" );
#endif
	return !result.trimmed().isEmpty();
}
Example #28
0
QString blockify(const QByteArray& s)
{
    const char* indent = "\n | ";
    QByteArray block = s.trimmed();
    block.replace('\n', indent);
    block.prepend(indent);
    block.append('\n');
    return block;
}
Example #29
0
QStringList Registry::readExcludedKeys(const QString sysfile, const QString path, const QStringList keys, const int count) const{
	QStringList ret;
	QString searchPath;

	searchPath="[";
	searchPath.append(path);
	searchPath.append("]");
	searchPath.replace("\\","\\\\");

	QString sfile = regfile;
	sfile.append(sysfile);
	sfile.append(".reg");

	QFile file(sfile);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
		qDebug()<<" [EE] Can't open reg file: "<<regfile;
		return ret;
	}

	bool readFlag=false;
	int readed=1;

	while (!file.atEnd()) {
		QByteArray line = file.readLine();

		if ((readFlag) && (!line.trimmed().isEmpty())){
			QList<QByteArray> key = line.trimmed().split('=');
			int index = keys.indexOf(key.at(0));
			if (index==-1){
				ret.append(line.trimmed());
				readed++;
				if (readed>count)
					return ret;
			}
		} else {
			if ((line.indexOf(searchPath)>-1) and (!readFlag))
				readFlag=true;
		}

		if (((line=="\n") or (line.isEmpty())) and (readFlag))
			readFlag=false;
	}
	return ret;
}
Example #30
0
void HTTPConnection::readHeaders() {
    while (_socket->canReadLine()) {
        QByteArray line = _socket->readLine();
        QByteArray trimmed = line.trimmed();
        if (trimmed.isEmpty()) {
            _socket->disconnect(this, SLOT(readHeaders()));

            QByteArray clength = requestHeader("Content-Length");
            if (clength.isEmpty()) {
                _parentManager->handleHTTPRequest(this, _requestUrl);

            } else {
                bool success = false;
                auto length = clength.toInt(&success);
                if (!success) {
                    qWarning() << "Invalid header." << _address << trimmed;
                    respond("400 Bad Request", "The header was malformed.");
                    return;
                }

                // Storing big requests in memory gets expensive, especially on servers
                // with limited memory. So we store big requests in a temporary file on disk
                // and map it to faster read/write access.
                static const int MAX_CONTENT_SIZE_IN_MEMORY = 10 * 1000 * 1000;
                if (length < MAX_CONTENT_SIZE_IN_MEMORY) {
                    _requestContent = MemoryStorage::make(length);
                } else {
                    _requestContent = FileStorage::make(length);
                }

                connect(_socket, SIGNAL(readyRead()), SLOT(readContent()));

                // read any content immediately available
                readContent();
            }
            return;
        }
        char first = line.at(0);
        if (first == ' ' || first == '\t') { // continuation
            _requestHeaders[_lastRequestHeader].append(trimmed);
            continue;
        }
        int idx = trimmed.indexOf(':');
        if (idx == -1) {
            qWarning() << "Invalid header." << _address << trimmed;
            respond("400 Bad Request", "The header was malformed.");
            return;
        }
        _lastRequestHeader = trimmed.left(idx).toLower();
        QByteArray& value = _requestHeaders[_lastRequestHeader];
        if (!value.isEmpty()) {
            value.append(", ");
        }
        value.append(trimmed.mid(idx + 1).trimmed());
    }
}