QJSON using in Mac - getting some issues - qt

I am using the QJson for parsing. But I am stuck up with some issues. I have used the following code:
void CityBook ::getCityList(QUrl url)
{
//!connect(cityReply, SIGNAL(readyRead()),this, SLOT(httpReadyRead()));
cityGuideNetworkAccessManager = new QNetworkAccessManager(this);
connect(cityGuideNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(httpReadyRead(QNetworkReply*)));
QNetworkRequest cityRequest(url);
cityGuideNetworkAccessManager->get(cityRequest);
}
void CityBook::httpReadyRead(QNetworkReply *reply)
{
QMessageBox::information(this, tr("HTTP"),
tr(reply->readAll()),QMessageBox::NoButton
);
QJson::Parser parser;
bool ok;
const QByteArray &resultbyte = reply->readAll();
qDebug() << resultbyte;
QVariant result1 = parser.parse(reply->readAll(), &ok);
qDebug() << result1;
QVariantList result=parser.parse(resultbyte,&ok).toList();
qDebug()<< result.size();
if (!ok)
{
qFatal("An error occurred during parsing");
exit (1);
}
qDebug() <<"error String"<< parser.errorString();
qDebug() <<"error" <parser.errorLine();
//! QVariantList entries = result["name"].toList();
foreach (QVariant city, result) {
QVariantMap names = city.toMap();
qDebug() << "\t-" << names.value("name");
}
}
The output is:
Starting /Users/QT Developement/CityBook-build-desktop/CityBook.app/Contents/MacOS/CityBook...
""
QVariant(, )
0
error String ""
error 0

The result of the readAll function is an empty byte array. According to documentation this can mean either that no data are available or that an error occurred.

Related

QNetwork Reply from QNetworkAccessManager

The following code is from an example shows how to use QNetworkAccessManager to download things.
void Downloader::replyFinished (QNetworkReply *reply)
{
if(reply->error())
{
qDebug() << "ERROR!";
qDebug() << reply->errorString();
}
else
{
qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString();
qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();
qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
QFile *file = new QFile("C:/Qt/Dummy/downloaded.txt");
if(file->open(QFile::Append))
{
file->write(reply->readAll());
file->flush();
file->close();
}
delete file;
}
reply->deleteLater();
}
My question is do we have to call reply->deleteLater(); here? If we don't call it, when we perform QNetworkAccessManager::get() call the second time, will the QNetworkReply* in the slot be the same QNetworkReply* ?
If you don't call deleteLater(), the QNetworkReply object will be leaked and its memory not freed. A second get() call will create a new QNetworkReply object.

How can I read the body from QNetworkReply if code is not 200

Reply returns empty body content if reply->error() != QNetworkReply::NoError,
but actually response has a content.
How can I read it?
void MainWindow::on_pushButton_clicked()
{
manager = new QNetworkAccessManager(this);
connect( manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://...")));
}
void MainWindow::replyFinished(QNetworkReply* reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QByteArray content= reply->readAll();
QDebug() << QString body(content); // ok
} else {
QByteArray content= reply->readAll();
QDebug() << QString body(content); //empty, but must be exist
}
}

QNetworkAccessManager request fail (CA signed certificate)

I've got a CA signed certificate which I use for a webservices. In Chrome and Firefox everything work fine.
Now I want to write a QT-client for the webservice. But all what I get is "connection closed" after 30 seconds. If I request "https://gmail.com" or "https://www.dfn.de/" I get a proper result.
Here is my code.
void Request::send() {
QUrl url("my url");
qDebug() << "URL: " << url;
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::UserAgentHeader, userAgent);
QObject::connect(manager, &QNetworkAccessManager::authenticationRequired, this, &Request::provideAuthenication);
QObject::connect(manager, &QNetworkAccessManager::finished, this , &Request::replyFinished);
QObject::connect(manager, &QNetworkAccessManager::sslErrors, this , &Request::sslErrors);
qDebug() << "fire request";
manager->get(request);
}
void Request::provideAuthenication(QNetworkReply *, QAuthenticator *ator) {
qDebug() << "provideAuthenication";
ator->setUser("***");
ator->setPassword("***");
}
void Request::replyFinished(QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError)
qDebug() << "Network Error: " << reply->errorString();
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute );
QVariant statusPhrase = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute );
qDebug() << "Result: " << statusCode.toInt() << " " << statusPhrase.toString();
qDebug() << "Data: " << reply->readAll();
}
void Request::sslErrors(QNetworkReply *, const QList<QSslError> &errors) {
foreach (const QSslError &error, errors) {
qDebug() << "SSL Error: " << error.errorString();
}
}
And that is the output. No sslError! No HTTP Error!
URL: QUrl( "my url" )
Network Error: "Connection closed"
Result: 0
Data: ""
So why hangs QT or the server? Did I miss something?!
It was a misconfiguration of openjdk7 (glassfish).
The hint of Aldaviva works on serverfault for me. https://serverfault.com/questions/389197/ssl-routinesssl23-writessl-handshake-failure
To bad that QT do not throw an ssl-error.

Qt: QGLShaderProgram turn off log messages

Is there a way to turn of log messages when calling QGLShaderProgram::link()?
http://qt-project.org/doc/qt-4.8/qglshaderprogram.html#link
Messages look like:
QGLShader::link: "Vertex shader(s) linked, fragment shader(s) linked.
"
Qt code looks like this:
src/opengl/qglshaderprogram.cpp:893
glLinkProgram(program);
value = 0;
glGetProgramiv(program, GL_LINK_STATUS, &value);
d->linked = (value != 0);
value = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &value);
d->log = QString();
if (value > 1) {
char *logbuf = new char [value];
GLint len;
glGetProgramInfoLog(program, value, &len, logbuf);
d->log = QString::fromLatin1(logbuf);
QString name = objectName();
if (name.isEmpty())
qWarning() << "QGLShader::link:" << d->log;
else
qWarning() << "QGLShader::link[" << name << "]:" << d->log;
delete [] logbuf;
}
return d->linked;
}
So it seems the only possible solution is to redirect qWarning() as done in: How to redirect qDebug, qWarning, qCritical etc output?
qInstallMsgHandler([](QtMsgType , const char* ) { }); // empty message handler
bool result = program.link();
qInstallMsgHandler(0); // restore default message handling

QXmlQuery and XSLT20: Resultant Output String is empty everytime, works well on shell(xmlpattern)

I am writing a class to parse Itunes Libray File using QXmlQuery and QT-XSLT.
Here's my sample code:
ItunesLibParser::ItunesLibParser()
{
pathToLib = QString("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
}
void ItunesLibParser::createXSLFile(QFile &inFile)
{
if (inFile.exists()) {
inFile.remove();
}
inFile.open(QIODevice::WriteOnly);
QTextStream out(&inFile);
out << QString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out << QString("<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
out << QString("<xsl:output method=\"text\" />");
out << QString("<xsl:template name=\"playlistNames\">");
out << QString("<xsl:value-of select=\"child::integer[preceding-sibling::key[1]='Playlist ID']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("<xsl:value-of select=\"child::string[preceding-sibling::key[1]='Name']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("</xsl:template>");
out << QString("<xsl:template match=\"/\">");
out << QString("<xsl:for-each select=\"plist/dict/array/dict\">");
out << QString("<xsl:call-template name=\"playlistNames\"/>");
out << QString("</xsl:for-each>");
out << QString("</xsl:template>");
out << QString("</xsl:stylesheet>");
inFile.close();
return;
}
void ItunesLibParser::dumpPlayList()
{
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(QUrl(pathToLib));
QFile xslFile("plist.xsl");
createXSLFile(xslFile);
query.setQuery(QUrl("plist.xsl"));
QStringList* outDump = new QStringList();
query.evaluateTo(outDump);
if(outDump != NULL) {
QStringList::iterator iter = (*outDump).begin();
for (; iter != (*outDump).end();
++iter)
//code flow doesn't come here. It means being() == end()
std::cout << (*iter).toLocal8Bit().constData() << std::endl;
}
return;
}
OutDump here doesn't contain data. While in Shell (xmlpatterns-4.7 mystlye.xsl itunes_music_library.xml ), If I run my Query I get proper output.
Is there anything, wrong I am doing while calling it programatically? I checked out plist.xsl is created properly, but my doubt is whether "/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml" this is getting loaded or not? Or there might be another reasons, I am confused. Is there any experts to throw some light onto problem, I will be glad.
Intead from reading from the file, I read the file into buffer and converted that int string as passed to setquery. That solved the problem.
Here's sample code for those who could face similar problem in future.
void ITunesMlibParser::parsePlayListItemXml(int plistId)
{
QXmlQuery xQuery(QXmlQuery::XSLT20);
QFile inFile("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
if (!inFile.open(QIODevice::ReadOnly)) {
return;
}
QByteArray bArray;
while (!inFile.atEnd()) {
bArray += inFile.readLine();
}
QBuffer xOriginalContent(&bArray);
xOriginalContent.open(QBuffer::ReadWrite);
xOriginalContent.reset();
if (xQuery.setFocus(&xOriginalContent))
std::cout << "File Loaded" << std::endl;
//..
//..
}
Thanks
Rakesh

Resources