// SELECT * FROM table_I WHERE id = primary_I LIMIT 1 std::vector< std::map<std::string, std::string> > PostgreAdapter::get(std::string table_I, std::map<std::string, std::string> where_I) { std::vector< std::map<std::string, std::string> > result; std::map<std::string, std::string>* tmp; pqxx::result res; std::ostringstream query(""); query << "SELECT * FROM " << table_I; query << makeWhere(where_I); try { res = mWorker->exec(query.str()); } catch (const std::exception& e) { mLogger->error(const_cast<char*>(e.what())); return result; } result = parseResponse(res); if (result.size() == 0) { mLogger->info("Record not found!"); } return result; }
// ********************************************************************* // Function: getDetections // /// \brief Retrieves detections from the LeddarOne and stores them /// in the Detections[] array // ********************************************************************** char LeddarOne::getDetections() { unsigned int crc = 0xFFFF; unsigned char dataBuffer[19] = {0}; unsigned int i = 0; unsigned int len = 0; unsigned char msgFound = 0; unsigned long startTime = millis(); unsigned char detcount = 0; clearDetections(); sendRequest(); startTime = millis(); while (!SerialPort.available()) { //wait up to 1000ms if (millis()-startTime > 1000) { return ERR_LEDDAR_NO_RESPONSE; } } return parseResponse(); }
void GameClient::slotReadyRead() { QDataStream in(tcpSocket); in.setVersion(QDataStream::Qt_4_7); for (;;) { if (!nextBlockSize) { if (tcpSocket->bytesAvailable() < sizeof(quint16)) break; in >> nextBlockSize; } if (tcpSocket->bytesAvailable() < nextBlockSize) break; QTime time; QString msg; QVariant msgArgs; in >> time >> msg >> msgArgs; parseResponse(msg, msgArgs); nextBlockSize = 0; } }
void YTVideoUrlFetcher::onProcessFinished(int code, QProcess::ExitStatus status) { qDebug() << "youtube-dl process finished, status:" << status << ", exit code:" << code; if (status == QProcess::NormalExit && code == 0) { QByteArray rawJson = _process->readAllStandardOutput(); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(rawJson, &error); if (error.error != QJsonParseError::NoError) { qCritical() << "JSON parse error:" << error.errorString(); emit failure(); } else { Q_ASSERT(!doc.isNull()); QVariantMap response = parseResponse(doc); if (!response.isEmpty()) { QVariantMap map = doc.toVariant().toMap(); Q_ASSERT(!map.isEmpty() && map.contains("id")); _response_cache.insert(map["id"].toString(), new QVariantMap(response)); emit success(response); } else { emit failure(); } } } else { qCritical() << "YouTubeDL process did not finish cleanly:" << _process->readAllStandardError(); emit failure(); } delete _process; _process = NULL; }
void YTChannel::maybeLoadfromAPI() { if (loading) return; if (channelId.isEmpty()) return; uint now = QDateTime::currentDateTime().toTime_t(); static const int refreshInterval = 60 * 60 * 24 * 10; if (loaded > now - refreshInterval) return; loading = true; #ifdef APP_YT3 QUrl url = YT3::instance().method("channels"); { QUrlQueryHelper urlHelper(url); urlHelper.addQueryItem("id", channelId); urlHelper.addQueryItem("part", "snippet"); } #else QUrl url("http://gdata.youtube.com/feeds/api/users/" + channelId); { QUrlQueryHelper urlHelper(url); urlHelper.addQueryItem("v", "2"); } #endif QObject *reply = The::http()->get(url); connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResponse(QByteArray))); connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(requestError(QNetworkReply*))); }
void acceptInput() { char line[256]; char input[256]; char request[256]; char response[256]; // infinite loop while(1) { // display prompt fputs(">> ", stderr); // accept input fgets(line, sizeof line, stdin); sscanf(line, "%s", input); // if input is "exit" if(strcmp(input, "exit") == 0) exit(0); // quit program else { fprintf(stdout, "String Entered %s, Characters read : %d\n", input, strlen(line) - 1); parseInput(input, request); submitRequest(request); acceptResponse(response); parseResponse(response); } } }
HttpResponse::HttpResponse(const char *data, std::size_t len) : statusCode_(0) { if (data == nullptr || len < HTTP_VERSION_OFFSET + 5) { throw KaaException("Empty response was given"); } parseResponse(data, len); }
static char *getAuthorizationToken(char *user, char *password) /* Authenticate against GenomeSpace * Returns a token like [IGYpFc1CNO7acOJicopKHBTCS6JwDgoy]*/ { //old url: safef(authUrl, sizeof authUrl, "https://%s:%[email protected]/identityServer/basic", encUser, encPassword); //old2: safef(authUrl, sizeof authUrl, "https://%s:%[email protected]:8443/identityServer/basic", encUser, encPassword); //old3: safef(authUrl, sizeof authUrl, "https://%s:%[email protected]/identityServer/basic", encUser, encPassword); char *iSU = getGenomeSpaceConfig("identityServerUrl"); char *authUrl = insertUserPasswordIntoUrl(iSU, user, password); int sd = netUrlOpen(authUrl); if (sd < 0) errAbort("failed to open socket for [%s]", authUrl); char *responseCode = NULL; char *authToken = parseResponse(sd, &responseCode); if (startsWith("401 ", responseCode)) return NULL; if (!sameString(responseCode, "200 OK")) errAbort("GenomeSpace getAuthorizationToken: %s", responseCode); freeMem(authUrl); return authToken; }
HttpResponse::HttpResponse(const std::string& data) : statusCode_(0) { if (data.length() < HTTP_VERSION_OFFSET + 5) { throw KaaException("Empty response was given"); } parseResponse(data.c_str(), data.length()); }
int8_t getRPCVersion(const char* host, uint16_t port, const char* auth) { char url[MAX_URL_LEN]; int8_t result = 0; char *response = NULL; HTTPResponse *res = NULL; const char *JSONstr = "{\n" "\"method\": \"session-get\",\n" "\"arguments\": {}\n" "}"; if(!host) { return 0; } snprintf( url, MAX_URL_LEN, "http://%s:%d/transmission/rpc", host, port); res = sendHTTPData(url, auth, JSONstr, strlen(JSONstr)); if(res != NULL && res->responseCode == 200) { dbg_printf(P_DBG, "[getRPCVersion] got response!"); response = parseResponse(res->data); if(response) { if(!strncmp(response, "success", 7)) { result = parseRPCVersion(res->data); dbg_printf(P_DBG, "[getRPCVersion] RPC version: %d", result); } am_free((void*)response); } HTTPResponse_free(res); } return result; }
//-------------------------------------------------------------- void ofxTwitter::newResponse(ofEventArgs& args) { if(dataRequested != "") { ofxJSONElement result; bool parsingSuccessful = result.parse(dataRequested); bool getSuccessful = parsingSuccessful; if (parsingSuccessful) { if(result.isMember("errors")) { getSuccessful = false; ofxJSONElement errors = result["errors"]; for(int i = 0; i < errors.size(); i++) { ofxJSONElement error = errors[i]; ofLogError("ofxTwitter::newResponse") << "error code: " << errors[i]["code"].asInt() << " message: " << error["message"].asString(); } } } if (getSuccessful) { if(bDiskCacheActive) result.save("cache.json",true); ofLogNotice("ofxTwitter::newResponse") << "Tweets received."; //cout << result.getRawString() << endl; parseResponse(result); } else { ofLogError("ofxTwitter::newResponse") << "Failed to get tweets" << endl; } dataRequested = ""; ofRemoveListener(ofEvents().update,this,&ofxTwitter::newResponse); } }
void AppReply::readBody() { qDebug() << "body_device readyRead"; this->body += this->body_device->readAll(); if (this->body_device->atEnd()) { parseResponse(); } }
std::string HTTPSimple::POST(std::string url, std::string &data) { splitUrlIntoPageHost(url); std::string response = buildRequest(std::string("POST"), data); send(response); http_code = parseResponse(response); return response; }
std::string HTTPSimple::GET(std::string url) { splitUrlIntoPageHost(url); std::string data = ""; data = buildRequest(std::string("GET"), data); send(data); http_code = parseResponse(data); return data; }
LLUserAuth::UserAuthcode LLUserAuth::authResponse() { if (!mResponder) { return mAuthResponse; } bool done = mResponder->is_finished(); if (!done) { if (mResponder->is_downloading()) { mAuthResponse = E_DOWNLOADING; } return mAuthResponse; } mLastTransferRateBPS = mResponder->transferRate(); mErrorMessage = mResponder->getReason(); // if curl was ok, parse the download area. CURLcode result = mResponder->result_code(); if (is_internal_http_error(mResponder->getStatus())) { // result can be a meaningless CURLE_OK in the case of an internal error. result = CURLE_FAILED_INIT; // Just some random error to get the default case below. } switch (result) { case CURLE_OK: mAuthResponse = parseResponse(); break; case CURLE_COULDNT_RESOLVE_HOST: mAuthResponse = E_COULDNT_RESOLVE_HOST; break; case CURLE_SSL_PEER_CERTIFICATE: mAuthResponse = E_SSL_PEER_CERTIFICATE; break; case CURLE_SSL_CACERT: mAuthResponse = E_SSL_CACERT; break; case CURLE_SSL_CONNECT_ERROR: mAuthResponse = E_SSL_CONNECT_ERROR; break; default: mAuthResponse = E_UNHANDLED_ERROR; break; } LL_INFOS2("AppInit", "Authentication") << "Processed response: " << result << LL_ENDL; // We're done with this data. mResponder = NULL; return mAuthResponse; }
bool CMyHttp::PostData(const char* data,size_t sz, int /*timeouts*/,CMyHttpResonse** ppr) { CMyHttpResonse* R = new CMyHttpResonse; if(!send(data,sz)){ throw "未能成功向服务器发送数据!"; } parseResponse(R); *ppr = R; return true; }
LLUserAuth::UserAuthcode LLUserAuth::authResponse() { if (!mTransaction) { return mAuthResponse; } bool done = mTransaction->process(); if (!done) { if (LLXMLRPCTransaction::StatusDownloading == mTransaction->status(0)) { mAuthResponse = E_DOWNLOADING; } return mAuthResponse; } mLastTransferRateBPS = mTransaction->transferRate(); int result; mTransaction->status(&result); mErrorMessage = mTransaction->statusMessage(); // if curl was ok, parse the download area. switch (result) { case CURLE_OK: mAuthResponse = parseResponse(); break; case CURLE_COULDNT_RESOLVE_HOST: mAuthResponse = E_COULDNT_RESOLVE_HOST; break; case CURLE_SSL_PEER_CERTIFICATE: mAuthResponse = E_SSL_PEER_CERTIFICATE; break; case CURLE_SSL_CACERT: mAuthResponse = E_SSL_CACERT; break; case CURLE_SSL_CONNECT_ERROR: mAuthResponse = E_SSL_CONNECT_ERROR; break; default: mAuthResponse = E_UNHANDLED_ERROR; break; } LL_INFOS2("AppInit", "Authentication") << "Processed response: " << result << LL_ENDL; delete mTransaction; mTransaction = NULL; return mAuthResponse; }
/** * Retrieves the details for the specified location * * @param pczLocation The string containing the name/code of the location * * @return A pointer to a list of LocationInfo entries, possibly empty, * if no details were found. Caller is responsible for freeing the list. */ GList * getLocationInfo(const gchar * pczLocation) { gint iRetCode = 0; gint iDataSize = 0; GList * pList = NULL; gchar * pcEscapedLocation = convertToASCII(pczLocation); gsize len = getWOEIDQueryLength(pcEscapedLocation); gchar * cQueryBuffer = g_malloc0(len); gint iRet = getWOEIDQuery(cQueryBuffer, pcEscapedLocation); g_free(pcEscapedLocation); LXW_LOG(LXW_DEBUG, "yahooutil::getLocationInfo(%s): query[%d]: %s", pczLocation, iRet, cQueryBuffer); gpointer pResponse = getURL(cQueryBuffer, &iRetCode, &iDataSize); if (!pResponse || iRetCode != HTTP_STATUS_OK) { LXW_LOG(LXW_ERROR, "yahooutil::getLocationInfo(%s): Failed with error code %d", pczLocation, iRetCode); } else { LXW_LOG(LXW_DEBUG, "yahooutil::getLocationInfo(%s): Response code: %d, size: %d", pczLocation, iRetCode, iDataSize); LXW_LOG(LXW_VERBOSE, "yahooutil::getLocation(%s): Contents: %s", pczLocation, (const char *)pResponse); iRet = parseResponse(pResponse, &pList, NULL); LXW_LOG(LXW_DEBUG, "yahooutil::getLocation(%s): Response parsing returned %d", pczLocation, iRet); if (iRet) { // failure g_list_free_full(pList, freeLocation); } } g_free(cQueryBuffer); g_free(pResponse); return pList; }
//-------------------------------------------------------------- void ofxTwitter::loadCacheFile() { ofLogNotice("ofxTwitter::loadCacheFile") << "Loading local file 'cache.json'"; ofxJSONElement result; bool parsingSuccessful = result.openLocal("cache.json"); if (parsingSuccessful) { parseResponse(result); } else { ofLogError("ofxTwitter::loadCacheFile") << "Failed to load JSON"; } }
LLUserAuth::UserAuthcode LLUserAuth::authResponse() { if (!mResponder) { return mAuthResponse; } bool done = mResponder->is_finished(); if (!done) { if (mResponder->is_downloading()) { mAuthResponse = E_DOWNLOADING; } return mAuthResponse; } mLastTransferRateBPS = mResponder->transferRate(); mErrorMessage = mResponder->reason(); // if curl was ok, parse the download area. CURLcode result = mResponder->result_code(); switch (result) { case CURLE_OK: mAuthResponse = parseResponse(); break; case CURLE_COULDNT_RESOLVE_HOST: mAuthResponse = E_COULDNT_RESOLVE_HOST; break; case CURLE_SSL_PEER_CERTIFICATE: mAuthResponse = E_SSL_PEER_CERTIFICATE; break; case CURLE_SSL_CACERT: mAuthResponse = E_SSL_CACERT; break; case CURLE_SSL_CONNECT_ERROR: mAuthResponse = E_SSL_CONNECT_ERROR; break; default: mAuthResponse = E_UNHANDLED_ERROR; break; } LL_INFOS2("AppInit", "Authentication") << "Processed response: " << result << LL_ENDL; // We're done with this data. mResponder = NULL; return mAuthResponse; }
AppReply::AppReply(const char* method, const QUrl &url, QIODevice *body_device, QObject *parent) : QNetworkReply(parent) { this->method = method; this->url = url; this->body_device = body_device; if (body_device) { qDebug() << "body_device connect"; connect(body_device, SIGNAL(readyRead()), this, SLOT(readBody())); } else { QTimer::singleShot(0, this, SLOT(parseResponse())); } }
uint32_t NTPClient::getEpochTime(const char* host, int port, unsigned long timeout) { if (host == NULL || port < 1) { return (uint32_t)-1; } prepareRequest(); sendRequest(host, port); if (!receiveResponse(timeout)) { return (uint32_t)-1; } return parseResponse(); }
void parserSelector(const Byte* bytes, size_t size, Log& logfile) { UINT64 signature = *((UINT64*)(bytes + 4)); if (signature == kRequestSignature) { parseRequest(bytes, logfile); } else if (signature == kResponseSignature) { parseResponse(bytes, logfile); } else { printf("invalid packet file\n"); } }
bool HttpRequest::send() { mError = ""; // check that TNL understands the supplied address if(!mRemoteAddress->isValid()) { mError = "Address invalid"; return false; } S32 connectError = mSocket->connect(*mRemoteAddress); if(connectError == UnknownError) { mError = "Connect error"; return false; } if(!mSocket->isWritable(FIVE_SECONDS)) { mError = "Socket not writable"; return false; } buildRequest(); if(!sendRequest(mRequest)) { mError = "Can't send request"; return false; } string response = receiveResponse(); if(response == "") { mError = "No response"; return false; } parseResponse(response); if(getResponseCode() == 0) { mError = "Invalid response code"; return false; } return true; }
char *gsUploadUrl(char *gsToken, char *user, char *uploadFileName, off_t contentLength, char *base64Md5, char *contentType) /* call uploadurl */ { // UPLOADURLS // TODO deal with creating parent dirs if uploadFileName contains a path? maybe not. // old: "https://identity.genomespace.org/datamanager/uploadurls/users/" // old "https://dm.genomespace.org/datamanager/v1.0/uploadurl/users/" // if this works, use default dir fetched earlier instead char *dmSvr = getGenomeSpaceConfig("dmServer"); char uploadUrl[1024]; safef(uploadUrl, sizeof(uploadUrl), "%s/v1.0/uploadurl/users/" "%s/" "%s" "?Content-Length=%lld" "&Content-MD5=%s" "&Content-Type=%s" , dmSvr , user , uploadFileName , (long long) contentLength , cgiEncode(base64Md5) , contentType ); struct dyString *reqExtra = newDyString(256); dyStringPrintf(reqExtra, "Cookie: gs-token=%s\r\n", gsToken); int sd = netOpenHttpExt(uploadUrl, "GET", reqExtra->string); if (sd < 0) errAbort("failed to open socket for [%s]", uploadUrl); char *responseCode = NULL; char *s3UploadUrl = parseResponse(sd, &responseCode); if (sameString(responseCode, "404 Not Found")) errAbort("GenomeSpace: %s, if a path was used in the output name, it may indicate the path does not exist in GenomeSpace.", responseCode); if (!sameString(responseCode, "200 OK")) errAbort("GenomeSpace: %s", responseCode); dyStringFree(&reqExtra); return s3UploadUrl; }
void xmlrpc_client_call2(xmlrpc_env * const envP, struct xmlrpc_client * const clientP, const xmlrpc_server_info * const serverInfoP, const char * const methodName, xmlrpc_value * const paramArrayP, xmlrpc_value ** const resultPP) { xmlrpc_mem_block * callXmlP; XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT_PTR_OK(clientP); XMLRPC_ASSERT_PTR_OK(serverInfoP); XMLRPC_ASSERT_PTR_OK(paramArrayP); makeCallXml(envP, methodName, paramArrayP, clientP->dialect, &callXmlP); if (!envP->fault_occurred) { xmlrpc_mem_block * respXmlP; xmlrpc_traceXml("XML-RPC CALL", XMLRPC_MEMBLOCK_CONTENTS(char, callXmlP), XMLRPC_MEMBLOCK_SIZE(char, callXmlP)); clientP->transportOps.call( envP, clientP->transportP, serverInfoP, callXmlP, &respXmlP); if (!envP->fault_occurred) { int faultCode; const char * faultString; xmlrpc_traceXml("XML-RPC RESPONSE", XMLRPC_MEMBLOCK_CONTENTS(char, respXmlP), XMLRPC_MEMBLOCK_SIZE(char, respXmlP)); parseResponse(envP, respXmlP, resultPP, &faultCode, &faultString); if (!envP->fault_occurred) { if (faultString) { xmlrpc_env_set_fault_formatted( envP, faultCode, "RPC failed at server. %s", faultString); xmlrpc_strfree(faultString); } else XMLRPC_ASSERT_VALUE_OK(*resultPP); } XMLRPC_MEMBLOCK_FREE(char, respXmlP); }
/** * Retrieves the forecast for the specified location WOEID * * @param pczWOEID The string containing the WOEID of the location * @param czUnits The character containing the units for the forecast (c|f) * @param pForecast The pointer to the forecast to be filled. If set to NULL, * a new one will be allocated. * */ void getForecastInfo(const gchar * pczWOEID, const gchar czUnits, gpointer * pForecast) { gint iRetCode = 0; gint iDataSize = 0; gsize len = getForecastQueryLength(pczWOEID); gchar * cQueryBuffer = g_malloc(len + 1); gint iRet = getForecastQuery(cQueryBuffer, pczWOEID, czUnits); LXW_LOG(LXW_DEBUG, "yahooutil::getForecastInfo(%s): query[%d]: %s", pczWOEID, iRet, cQueryBuffer); gpointer pResponse = getURL(cQueryBuffer, &iRetCode, &iDataSize); if (!pResponse || iRetCode != HTTP_STATUS_OK) { LXW_LOG(LXW_ERROR, "yahooutil::getForecastInfo(%s): Failed with error code %d", pczWOEID, iRetCode); } else { LXW_LOG(LXW_DEBUG, "yahooutil::getForecastInfo(%s): Response code: %d, size: %d", pczWOEID, iRetCode, iDataSize); LXW_LOG(LXW_VERBOSE, "yahooutil::getForecastInfo(%s): Contents: %s", pczWOEID, (const char *)pResponse); iRet = parseResponse(pResponse, NULL, pForecast); LXW_LOG(LXW_DEBUG, "yahooutil::getForecastInfo(%s): Response parsing returned %d", pczWOEID, iRet); if (iRet) { freeForecast(*pForecast); *pForecast = NULL; } } g_free(cQueryBuffer); g_free(pResponse); }
void SuggestionQueryEngine::replyReceived(QNetworkReply *networkReply) { if (networkReply->error() == QNetworkReply::NoError) { QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jsonObject = document.object(); QJsonValue dataValue = jsonObject["data"]; if (dataValue.isArray()) { QVector<SuggestionArtwork*> suggestionArtworks; parseResponse(dataValue.toArray(), suggestionArtworks); m_Suggestor->setSuggestedArtworks(suggestionArtworks); } } else { qWarning() << "Keywords suggestion error:" << networkReply->errorString(); } m_Suggestor->unsetInProgress(); networkReply->deleteLater(); }
// ********************************************************************* // Function: getDetections // /// \brief Retrieves detections from the Leddar and stores them /// in the Detections[] array // ********************************************************************** char Leddar16::getDetections() { unsigned long startTime; clearDetections(); sendRequest(); //Sends the request for detections on serial port startTime = millis(); while (!SerialPort.available()) { // wait up to 1000ms if (millis()-startTime > 1000) { return ERR_LEDDAR_NO_RESPONSE; } } return parseResponse(); // Parses the data available on the serial port }
void parseResponse (xmlDocPtr xml_doc, xmlNodePtr xml_node_parent) { xmlNodePtr xml_node; xmlChar *buf; /* if ((!xmlStrcmp(xml_node_parent->name, (const xmlChar *)"return"))) { buf = (char*)xmlNodeListGetString(xml_doc, xml_node_parent->xmlChildrenNode, 1); printf ("Return %s Buf: %s\n", xml_node_parent->name, buf); xmlFree(buf); printf ("Type %s\n", xmlGetProp(xml_node_parent, "arrayType")); } */ /* if ((!xmlStrcmp(xml_node_parent->name, (const xmlChar *)"item"))) { if (xmlStrstr(xmlGetProp(xml_node_parent, "type"), "Migration")) { migrationPtr ret = NULL; ret = (migrationPtr) malloc(sizeof(migration)); ret = parseMigration (xml_doc, xml_node_parent, ret); printf ("Version: %s | Time: %s\n", ret->version, ret->apply_time); return; } } */ xml_node = xml_node_parent->xmlChildrenNode; while (xml_node != NULL) { buf = (char*)xmlNodeListGetString(xml_doc, xml_node->xmlChildrenNode, 1); printf ("%s : %s\n", xml_node->name, buf); xmlFree(buf); buf = NULL; parseResponse (xml_doc, xml_node); xml_node = xml_node->next; } return; }