bool sendCommandJSON(const std::string & method, Poco::Dynamic::Var & output, const std::vector<Poco::Dynamic::Var> & params = std::vector<Poco::Dynamic::Var>()) { // Create request Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/jsonrpc"); // Authorization request.set("Authorization", "Basic bnpiZ2V0OnRlZ2J6bg=="); // Create body Poco::Dynamic::Var body = Poco::Dynamic::Struct<std::string>(); body["method"] = method; body["id"] = "sendCommandJSON"; std::vector<Poco::Dynamic::Var> params_; params_.push_back("callback"); for (std::vector<Poco::Dynamic::Var>::const_iterator it = params.begin(); it != params.end(); ++it) { params_.push_back(*it); } body["params"] = params_; std::string body_ = MyVideoCollection::JSON::stringify(body); request.setContentLength(body_.length()); // Send request Poco::Net::HTTPClientSession session("127.0.0.1", port_); session.sendRequest(request) << body_ << std::flush; // Receive response Poco::Net::HTTPResponse response; std::istream & responseStream = session.receiveResponse(response); std::size_t bytes = response.getContentLength(); std::stringstream response_; while (bytes > 0 && responseStream.good()) { char buf[4096]; responseStream.read(buf, std::min(bytes, (std::size_t)4096)); std::size_t gcount = responseStream.gcount(); bytes -= gcount; response_ << std::string(buf, gcount); } // Parse JSON output = MyVideoCollection::JSON::parse(response_); // Result? if (!output.isStruct()) { output.empty(); return false; } output = output["result"]; return true; }
Pothos::Object ProxyBlockEval::lookupOrEvalAsType(const Poco::Dynamic::Var &arg) { //this is not an expression, but a native JSON type if (not arg.isString()) return _evalEnv->eval(arg.toString()); //the expression is an already evaluated property const auto expr = arg.extract<std::string>(); if (_properties.count(expr) != 0) return _properties.at(expr); //otherwise the expression must be evaluated //with the evaluated properties as global variables //use a new eval to avoid poisoning the globals Pothos::Util::EvalEnvironment evalEnv; for (const auto &pair : _properties) { //Register can fail for non-primitive types //but those are not used in expressions anyway. try {evalEnv.registerConstantObj(pair.first, pair.second);} catch (...){} } return evalEnv.eval(expr); }
void RowFilter::doCompare(Poco::Dynamic::Var& ret, Poco::Dynamic::Var& val, CompT comp, const ComparisonEntry& ce) { if (ret.isEmpty()) ret = comp(val, ce.get<0>()); else { if (ce.get<2>() == OP_OR) ret = ret || comp(val, ce.get<0>()); else if (ce.get<2>() == OP_AND) ret = ret && comp(val, ce.get<0>()); else throw IllegalStateException("Unknown logical operation."); } }
void Controller::searchSimilarRequest(std::map<std::string, std::string>& params, const Poco::Dynamic::Var& request) { Record record; vector<uint8_t>* image_data = NULL; int count = 10; if (params.count("blockHash")) { record.getHashes()[BlockHash] = str2bin(params["blockHash"]); } if (params.count("dHash")) { record.getHashes()[DHash] = str2bin(params["dHash"]); } if (params.count("gaussDHash")) { record.getHashes()[GaussDHash] = str2bin(params["gaussDHash"]); } if (params.count("gauss2DHash")) { record.getHashes()[Gauss2DHash] = str2bin(params["gauss2DHash"]); } if (params.count("gaussBlockHash")) { record.getHashes()[GaussBlockHash] = str2bin(params["gaussBlockHash"]); } if (params.count("url")) { image_data = Image::fromUrl(params["url"]); } if (params.count("count")) { count = atoi(params["count"].c_str()); } if (!request.isEmpty()) { Poco::JSON::Object::Ptr json = request.extract<Poco::JSON::Object::Ptr>(); if (!image_data && json->has("image_base64")) { image_data = Image::fromBase64(json->getValue<string>("image_base64")); } if (!image_data && json->has("image_url")) { image_data = Image::fromUrl(json->getValue<string>("image_url")); } } if (image_data) { HashAlgorithmManager::getInstance().attachSimilarHashes(record, image_data); delete image_data; } appio::print_ok(HashManager::getInstance().searchSimilar(record, count)); }
void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { _parameters = parameters; _request = &request; _response = &response; if ( _parameters.size() > 0 ) { _action = _parameters.front(); _parameters.erase(_parameters.begin()); } else { setResponseStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Invalid URI parameters"); return; } for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it) { int pos = it->find_first_of(':'); if ( pos != std::string::npos ) { std::string name = it->substr(0, pos); std::string value = it->substr(pos+1); _namedParameters[name] = value; } } std::string contentType = request.getContentType(); if ( contentType == "application/json" ) { Poco::JSON::Parser parser; try { Poco::Dynamic::Var json = parser.parse(request.stream()); if ( ! json.isEmpty() && json.type() == typeid(Poco::JSON::Object::Ptr) ) { _data->set("filter", json.extract<Poco::JSON::Object::Ptr>()); } } catch(Poco::JSON::JSONException& jsone) { // Make sure everything is read, otherwise this can result // in Bad Request error in the next call. Poco::NullOutputStream nos; Poco::StreamCopier::copyStream(request.stream(), nos); setResponseStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "JSON error occurred: " + jsone.displayText()); return; } } else { _form.load(request, request.stream(), *this); } // Make sure everything is read, otherwise this can result // in Bad Request error in the next call. Poco::NullOutputStream nos; Poco::StreamCopier::copyStream(request.stream(), nos); beforeAction(); if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK || _data->has("error") ) { //TODO: return error template file or json error } const ActionMap& actions = getActions(); ActionMap::const_iterator it = actions.find(_action); if ( it == actions.end() ) { setResponseStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, "Invalid action '" + _action + "' specified."); return; } ActionFn action = it->second; (this->*action)(); afterAction(); }
bool RowFilter::isAllowed(std::size_t row) const { Poco::Dynamic::Var retVal; const RecordSet& rs = recordSet(); std::size_t columns = rs.columnCount(); ComparisonMap::const_iterator it = _comparisonMap.begin(); ComparisonMap::const_iterator end = _comparisonMap.end(); for (; it != end; ++it) { for (std::size_t col = 0; col < columns; ++col) { const std::string name = toUpper(rs.metaColumn(static_cast<UInt32>(col)).name()); if (_comparisonMap.find(name) == _comparisonMap.end()) continue; Poco::Dynamic::Var ret; CompT compOp = 0; Poco::Dynamic::Var val = rs.value(col, row, false); switch (it->second.get<1>()) { case VALUE_LESS_THAN: compOp = less; break; case VALUE_LESS_THAN_OR_EQUAL: compOp = lessOrEqual; break; case VALUE_EQUAL: compOp = equal; break; case VALUE_GREATER_THAN: compOp = greater; break; case VALUE_GREATER_THAN_OR_EQUAL: compOp = greaterOrEqual; break; case VALUE_NOT_EQUAL: compOp = notEqual; break; case VALUE_IS_NULL: compOp = isNull; break; default: throw IllegalStateException("Unsupported comparison criteria."); } doCompare(ret, val, compOp, it->second); if (retVal.isEmpty()) retVal = ret; else retVal = retVal || ret; } } // iterate through children FilterMap::const_iterator fIt = _filterMap.begin(); FilterMap::const_iterator fEnd = _filterMap.end(); for (; fIt != fEnd; ++fIt) { if (OP_OR == fIt->second) { if (retVal.isEmpty()) retVal = fIt->first->isAllowed(row); else retVal = retVal || fIt->first->isAllowed(row); } else if (OP_AND == fIt->second) { if (retVal.isEmpty()) retVal = fIt->first->isAllowed(row); else retVal = retVal && fIt->first->isAllowed(row); } else throw IllegalStateException("Unknown logical operation."); } if (retVal.isEmpty()) retVal = true; // no filtering found return (!_not) && retVal.extract<bool>(); }
void QueueManager::connect(const Poco::DynamicStruct& connectionInformation) { MQCNO cno = { MQCNO_DEFAULT }; cno.Version = MQCNO_VERSION_2; cno.Options = MQCNO_HANDLE_SHARE_BLOCK; MQCD cd = { MQCD_CLIENT_CONN_DEFAULT }; const std::string channel = connectionInformation["channel"]; const std::string connection = connectionInformation["connection"]; strncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH); strncpy(cd.ConnectionName, connection.c_str(), MQ_CONN_NAME_LENGTH); cd.TransportType = MQXPT_TCP; cno.ClientConnPtr = &cd; // User/Password needs at least MQCNO version 5 #ifdef MQCNO_VERSION_5 MQCSP csp = { MQCSP_DEFAULT }; if (connectionInformation.contains("user")) { const std::string user = connectionInformation["user"]; if (user.length() > 0 ) { const std::string pwd = connectionInformation["pwd"]; csp.AuthenticationType = MQCSP_AUTH_USER_ID_AND_PWD; csp.CSPUserIdPtr = (MQPTR)user.c_str(); csp.CSPUserIdLength = (MQLONG)user.length(); csp.CSPPasswordPtr = (MQPTR)pwd.c_str(); csp.CSPPasswordLength = (MQLONG)pwd.length(); cno.SecurityParmsPtr = &csp; cno.Version = MQCNO_VERSION_5; } } #endif // SSL needs at least MQCNO version 4 // SSL requires MQCD version 7 or later #if defined(MQCNO_VERSION_4) && defined(MQCD_VERSION_7) MQSCO sco = { MQSCO_DEFAULT }; MQAIR authInfoRec = { MQAIR_DEFAULT }; if (connectionInformation.contains("ssl")) { if (cno.Version == MQCNO_VERSION_2) { cno.Version = MQCNO_VERSION_4; } const Poco::DynamicStruct ssl = connectionInformation["ssl"].extract<Poco::DynamicStruct>(); if (ssl.contains("cipherspec")) { strncpy(cd.SSLCipherSpec, ssl["cipherspec"].toString().c_str(), MQ_SSL_CIPHER_SPEC_LENGTH); cd.Version = MQCD_VERSION_7; } Poco::Dynamic::Var keyrepos = ssl["keyrepos"]; strncpy(sco.KeyRepository, keyrepos.toString().c_str(), MQ_SSL_KEY_REPOSITORY_LENGTH); if (ssl.contains("fips")) { if (ssl["fips"].convert<bool>()) { sco.FipsRequired = MQSSL_FIPS_YES; sco.Version = MQSCO_VERSION_2; // A version 2 MQSCO supports FipsRequired } } if (ssl.contains("suiteb")) { static std::map<std::string, MQLONG> suiteBTable; if (suiteBTable.size() == 0) { suiteBTable.insert(std::make_pair("none", MQ_SUITE_B_NONE)); suiteBTable.insert(std::make_pair("128 bit", MQ_SUITE_B_128_BIT)); suiteBTable.insert(std::make_pair("192 bit", MQ_SUITE_B_192_BIT)); } sco.Version = MQSCO_VERSION_3; /* A version 3 MQSCO supports Suite B encryption policy */ Poco::StringTokenizer tokenizer(ssl["suiteb"].toString(), ",", Poco::StringTokenizer::TOK_TRIM); int n = 0; for (Poco::StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end() && n < 4; ++it, ++n) { std::map<std::string, MQLONG>::iterator suiteBIterator = suiteBTable.find(*it); if (suiteBIterator == suiteBTable.end()) { throw Poco::NotFoundException(Poco::format("Unknown SuiteB value: %s", *it)); } else { sco.EncryptionPolicySuiteB[n] = suiteBIterator->second; } } } if (ssl.contains("certificate_validation_policy")) { static std::map<std::string, MQLONG> certValPolicyTable; if (certValPolicyTable.size() == 0) { certValPolicyTable.insert(std::make_pair("any", MQ_CERT_VAL_POLICY_ANY)); certValPolicyTable.insert(std::make_pair("rfc5280", MQ_CERT_VAL_POLICY_RFC5280)); } sco.Version = MQSCO_VERSION_4; /* A version 4 MQSCO supports certificate validation policy */ std::string certValPolicy = ssl["certificate_validation_policy"].toString(); std::map<std::string, MQLONG>::iterator certValPolicyIterator = certValPolicyTable.find(certValPolicy); if (certValPolicyIterator == certValPolicyTable.end()) { throw Poco::NotFoundException(Poco::format("Unknown Certification Validation Policy: %s", certValPolicy)); } else { sco.CertificateValPolicy = certValPolicyIterator->second; } } if (ssl.contains("ocsp_url")) { /* OCSP requires MQAIR version 2 or later */ authInfoRec.Version = MQAIR_VERSION_2; authInfoRec.AuthInfoType = MQAIT_OCSP; strncpy(authInfoRec.OCSPResponderURL, ssl["ocsp_url"].toString().c_str(), MQ_AUTH_INFO_OCSP_URL_LENGTH); /* The MQSCO must point to the MQAIR */ sco.AuthInfoRecCount = 1; sco.AuthInfoRecPtr = &authInfoRec; } cno.SSLConfigPtr = &sco; } #endif MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>(); _handle = mqSystem.functions().connx(_name, &cno); inquireQmgrAttrs(); }
void Controller::ingestRequest(const Poco::Dynamic::Var& request) { if (request.type() != typeid(Poco::JSON::Array::Ptr)) { throw RequestException("Invalid JSON format, root must be array."); } try { Poco::JSON::Array::Ptr jsonArray = request.extract<Poco::JSON::Array::Ptr>(); for (Poco::JSON::Array::ConstIterator it = jsonArray->begin(); it != jsonArray->end(); it++) { Poco::JSON::Object::Ptr json = it->extract<Poco::JSON::Object::Ptr>(); Record record; vector<uint8_t>* image_data = NULL; if (json->has("id")) { record.setId(json->getValue<string>("id")); } if (json->has("thumbnail")) { record.setThumbnail(json->getValue<string>("thumbnail")); } if (json->has("metadata")) { record.setMetadata(json->getValue<string>("metadata")); } if (json->has("blockHash")) { record.getHashes()[BlockHash] = str2bin(json->getValue<string>("blockHash")); } if (json->has("dHash")) { record.getHashes()[DHash] = str2bin(json->getValue<string>("dHash")); } if (json->has("gaussDHash")) { record.getHashes()[GaussDHash] = str2bin(json->getValue<string>("gaussDHash")); } if (json->has("gauss2DHash")) { record.getHashes()[Gauss2DHash] = str2bin(json->getValue<string>("gauss2DHash")); } if (json->has("gaussBlockHash")) { record.getHashes()[GaussBlockHash] = str2bin(json->getValue<string>("gaussBlockHash")); } if (json->has("image_base64")) { image_data = Image::fromBase64(json->getValue<string>("image_base64")); } if (!image_data && json->has("image_url")) { image_data = Image::fromUrl(json->getValue<string>("image_url")); } if (json->has("status")) { string status = json->getValue<string>("status"); if (status == "deleted") { deleteRequest(record); continue; } else { throw RequestException("Invalid status value."); } } if (image_data) { HashAlgorithmManager::getInstance().attachHashes(record, image_data); delete image_data; } putRequest(record); } } catch (Poco::JSON::JSONException& e) { throw RequestException("Invalid JSON format."); } appio::print_ok("Data was successfully changed."); }