本文整理汇总了C++中json::Reader类的典型用法代码示例。如果您正苦于以下问题:C++ Reader类的具体用法?C++ Reader怎么用?C++ Reader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Reader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Parse
//.........这里部分代码省略.........
doc = *tok_iter;
break;
case 1:
key = *tok_iter;
break;
default:
break;
}
}
cmd.type_ = Command::Read;
cmd.docName_ = doc;
cmd.key_ = atoi(key.c_str());
}
else if (this->parser.method == HTTP_POST)
*/{
std::string cmdType;
std::string doc;
std::string key;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep("/");
tokenizer tokens(rest, sep);
int idx = 0;
for (tokenizer::iterator tok_iter = tokens.begin();
tok_iter != tokens.end(); ++tok_iter, idx++)
{
switch(idx)
{
case 0:
cmdType = *tok_iter;
case 1:
doc = *tok_iter;
break;
case 2:
key = *tok_iter;
break;
default:
break;
}
}
ACE_DEBUG((LM_DEBUG,ACE_TEXT ("Cmd Type : %s\n"), cmdType.c_str()));
if (boost::iequals(cmdType, "create"))
{
cmd.type_ = Command::CreateDocument;
}
else if (boost::iequals(cmdType, "drop"))
{
cmd.type_ = Command::DeleteDocument;
}
else if (boost::iequals(cmdType, "insert"))
{
cmd.type_ = Command::Create;
}
else if (boost::iequals(cmdType, "read"))
{
cmd.type_ = Command::Read;
}
else if (boost::iequals(cmdType, "delete"))
{
cmd.type_ = Command::Delete;
}
else if (boost::iequals(cmdType, "update"))
{
cmd.type_ = Command::Update;
}
cmd.docName_ = doc;
if(!key.empty())
cmd.key_.key_ = boost::lexical_cast<QWORD>(key.c_str());
cmd.value_.rev_ = 0;
if(this->request.bodySize > 0)
{
ACE_DEBUG((LM_DEBUG,ACE_TEXT ("Body Parsing...\n")));
Json::Reader reader;
std::string body(&data[this->request.bodyOffset], this->request.bodySize);
bool parsingSuccessful = reader.parse(body, cmd.value_.data_);
if ( !parsingSuccessful )
{
cmd.type_ = Command::None;
return cmd;
}
}
}
/*
else
{
cmd.type_ = Command::None;
}*/
return cmd;
}
示例2: main
int main(int argc, char* argv[])
{
std::string fileName;
int returnAmount = -1;
fileName = argv[1];
returnAmount = atoi(argv[2]);
std::ifstream t(fileName);
std::string JSONData((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
std::string searchKey = "";
for(int x = 3; x < argc; x++)
if(x > 3)
searchKey += " " + std::string(argv[x]);
else
searchKey += std::string(argv[x]);
Json::Value root;
Json::Reader reader;
bool parsedSuccess = reader.parse(JSONData, root, false);
std::vector<int> compareOverlayValues;
std::vector<int> TotalValues;
std::vector<int> placeVector;
double score = 0;
bool adding;
bool hasTag;
for(int place = 0; place < root.size(); place++)
{
adding = false;
hasTag = false;
score = 0;
score = compareShift(searchKey, root[place]["Name"].asString());
if(score == 1 || score == 0)
adding = true;
for(int tag = 0; tag < root[place]["Tags"].size(); tag++)
{
if(searchKey == root[place]["Tags"][tag].asString())
{
hasTag = true;
adding = true;
}
}
if(adding)
{
compareOverlayValues.push_back(compareOverlay(searchKey, root[place]["Name"].asString()));
score = (double)compareOverlayValues.at(compareOverlayValues.size()-1)/(score+1);
if(hasTag)
score += 30;
score += sqrt(root[place]["Score"].asInt()*10);
TotalValues.push_back(score);
placeVector.push_back(place);
}
}
if(returnAmount >= placeVector.size())
returnAmount = placeVector.size()-1;
if(TotalValues.size() > 0 && returnAmount < placeVector.size())
{
auto zipped = view::zip(placeVector, TotalValues);
sort(zipped, less{}, get_n<1>{});
for(int place = 0; place <= returnAmount; place++)
std::cout << root[placeVector.at(placeVector.size()-1-place)]["ID"] << std::endl;// << TotalValues.at(placeVector.size()-1-place) << std::endl;
}
return 0;
}
示例3: loadPreferences
void MadeupWindow::loadPreferences() {
canvas->makeCurrent();
try {
std::ifstream in(config_path);
Json::Reader reader;
Json::Value prefs;
reader.parse(in, prefs);
int width = prefs.get("window.width", 1200).asUInt();
int height = prefs.get("window.height", 600).asUInt();
resize(width, height);
int x = prefs.get("window.x", -1).asInt();
int y = prefs.get("window.y", -1).asInt();
if (x >= 0 && y >= 0) {
move(x, y);
}
float stroke_width = (float) prefs.get("path.stroke.width", renderer->getPathStrokeWidth()).asDouble();
renderer->setPathStrokeWidth(stroke_width);
path_stroke_width_spinner->setValue(stroke_width);
float vertex_size = (float) prefs.get("vertex.size", renderer->getVertexSize()).asDouble();
renderer->setVertexSize(vertex_size);
vertex_size_spinner->setValue(vertex_size);
string font_face = prefs.get("font.face", "Courier New").asString();
int font_size = prefs.get("font.size", 18).asUInt();
QFont font;
font.setFamily(font_face.c_str());
font.setPointSize(font_size);
editor->setFont(font);
console->setFont(font);
renderer->showHeading(prefs.get("show.heading", renderer->showHeading()).asBool());
show_heading_checkbox->setChecked(renderer->showHeading());
renderer->showHeading(prefs.get("show.path", renderer->showPath()).asBool());
show_path_checkbox->setChecked(renderer->showPath());
renderer->showStops(prefs.get("show.stops", renderer->showStops()).asBool());
show_stops_checkbox->setChecked(renderer->showStops());
Json::Value show_axis_node = prefs.get("show.axis", Json::nullValue);
Json::Value show_grid_node = prefs.get("show.grid", Json::nullValue);
Json::Value grid_extent_node = prefs.get("grid.extent", Json::nullValue);
Json::Value grid_spacing_node = prefs.get("grid.spacing", Json::nullValue);
for (int d = 0; d < 3; ++d) {
bool show_axis = show_axis_node.get(Json::ArrayIndex(d), renderer->showAxis(d)).asBool();
renderer->showAxis(d, show_axis);
show_axis_checkboxes[d]->setChecked(renderer->showAxis(d));
bool show_grid = show_grid_node.get(Json::ArrayIndex(d), renderer->showGrid(d)).asBool();
renderer->showGrid(d, show_grid);
show_grid_checkboxes[d]->setChecked(renderer->showGrid(d));
float grid_extent = (float) grid_extent_node.get(Json::ArrayIndex(d), renderer->getGridExtent(d)).asDouble();
renderer->setGridExtent(d, grid_extent);
grid_extent_spinners[d]->setValue(renderer->getGridExtent(d));
float grid_spacing = (float) grid_spacing_node.get(Json::ArrayIndex(d), renderer->getGridSpacing(d)).asDouble();
renderer->setGridSpacing(d, grid_spacing);
grid_spacing_spinners[d]->setValue(renderer->getGridSpacing(d));
}
// Background color
Json::Value background_color_node = prefs.get("background.color", Json::nullValue);
if (!background_color_node.isNull()) {
td::QVector4<float> color = renderer->getBackgroundColor();
for (int i = 0; i < 4; ++i) {
color[i] = (float) background_color_node.get(i, 0.0).asDouble();
}
renderer->setBackgroundColor(color);
}
QPalette background_color_palette;
background_color_palette.setColor(QPalette::Button, toQColor(renderer->getBackgroundColor()));
background_color_button->setPalette(background_color_palette);
// Path color
Json::Value path_color_node = prefs.get("path.color", Json::nullValue);
if (!path_color_node.isNull()) {
td::QVector4<float> color = renderer->getPathColor();
for (int i = 0; i < 4; ++i) {
color[i] = (float) path_color_node.get(i, 0.0).asDouble();
}
renderer->setPathColor(color);
}
QPalette path_color_palette;
path_color_palette.setColor(QPalette::Button, toQColor(renderer->getPathColor()));
path_color_button->setPalette(path_color_palette);
// Vertex color
Json::Value vertex_color_node = prefs.get("vertex.color", Json::nullValue);
if (!vertex_color_node.isNull()) {
//.........这里部分代码省略.........
示例4: exit
render::render(std::string manifest)
{
std::string in = get_file_contents(manifest.c_str());
Json::Value root;
Json::Reader reader;
bool stat = reader.parse( in, root );
if (stat){
FONT_NAME_ARIAL = root["FontArial"].asString();
FONT_NAME_COMIC = root["FontComic"].asString();
WINDOW_SIZE_X = root["WindowSize"]["x"].asInt();
WINDOW_SIZE_Y = root["WindowSize"]["y"].asInt();
TILE_SIZE = root["TileSize"].asInt();
BATTLEBACKGROUND = root["BattleBackground"].asString();
FRAME = root["Frame"].asString();
FRAME_SIDE = root["FrameSide"].asString();
FRAME_TITLE = root["FrameTitle"].asString();
CHAR_MENU = root["CharMenuOption"].asString();
CHAR_MENU_SELECTED = root["CharMenuSelect"].asString();
PROMPT = root["Prompt"].asString();
BATTLEMENU = root["BattleMenu"].asString();
}else{
std::cout << "Failed to parse manifest\n" << reader.getFormatedErrorMessages();
exit(128);
}
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
throw(122);
}
win = SDL_CreateWindow("RPG", 100, 100, WINDOW_SIZE_X, WINDOW_SIZE_Y,
SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
throw(122);
}
ren = SDL_CreateRenderer(win, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
throw(122);
}
TTF_Init();
font_arial16 = TTF_OpenFont(FONT_NAME_ARIAL.c_str(), 16);
font_comic16 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 16);
font_comic32 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 32);
font_comic50 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 50);
if (font_arial16 == nullptr){
std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl;
throw(122);
}
if (font_comic16 == nullptr){
std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl;
throw(122);
}
if (font_comic32 == nullptr){
std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl;
throw(122);
}
if (font_comic50 == nullptr){
std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl;
throw(122);
}
}
示例5: operator
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
bool gotDevice;
#ifdef OSVR_MULTISERVER_VERBOSE
bool first = true;
#endif
do {
gotDevice = false;
struct hid_device_info *enumData = hid_enumerate(0, 0);
for (struct hid_device_info *dev = enumData; dev != nullptr;
dev = dev->next) {
if (m_isPathHandled(dev->path)) {
continue;
}
#ifdef OSVR_MULTISERVER_VERBOSE
if (first) {
std::cout << "[OSVR Multiserver] HID Enumeration: "
<< boost::format("0x%04x") % dev->vendor_id << ":"
<< boost::format("0x%04x") % dev->product_id
<< std::endl;
}
#endif
if (gotDevice) {
continue;
}
// Razer Hydra
if (dev->vendor_id == 0x1532 && dev->product_id == 0x0300) {
gotDevice = true;
m_handlePath(dev->path);
auto hydraJsonString = osvr::util::makeString(
com_osvr_Multiserver_RazerHydra_json);
Json::Value hydraJson;
Json::Reader reader;
if (!reader.parse(hydraJsonString, hydraJson)) {
throw std::logic_error("Faulty JSON file for Hydra - "
"should not be possible!");
}
/// Decorated name for Hydra
std::string name;
{
// Razer Hydra
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
name =
reg.useDecoratedName(m_data.getName("RazerHydra"));
reg.registerDevice(new vrpn_Tracker_RazerHydra(
name.c_str(), reg.getVRPNConnection()));
reg.setDeviceDescriptor(hydraJsonString);
}
std::string localName = "*" + name;
{
// Copy semantic paths for corresponding filter: just
// want left/$target and right/$target
Json::Value filterJson;
if (!reader.parse(
osvr::util::makeString(
com_osvr_Multiserver_OneEuroFilter_json),
filterJson)) {
throw std::logic_error("Faulty JSON file for One "
"Euro Filter - should not "
"be possible!");
}
auto &filterSem =
(filterJson["semantic"] = Json::objectValue);
auto &hydraSem = hydraJson["semantic"];
for (auto const &element : {"left", "right"}) {
filterSem[element] = Json::objectValue;
filterSem[element]["$target"] =
hydraSem[element]["$target"];
}
auto &filterAuto = (filterJson["automaticAliases"] =
Json::objectValue);
filterAuto["$priority"] =
130; // enough to override a normal automatic route.
auto &hydraAuto = hydraJson["automaticAliases"];
for (auto const &element :
{"/me/hands/left", "/me/hands/right"}) {
filterAuto[element] = hydraAuto[element];
}
// Corresponding filter
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
reg.registerDevice(new vrpn_Tracker_FilterOneEuro(
reg.useDecoratedName(
m_data.getName("OneEuroFilter")).c_str(),
reg.getVRPNConnection(), localName.c_str(), 2, 1.15,
1.0, 1.2, 1.5, 5.0, 1.2));
reg.setDeviceDescriptor(filterJson.toStyledString());
}
continue;
}
// OSVR Hacker Dev Kit
if ((dev->vendor_id == 0x1532 && dev->product_id == 0x0300) ||
(dev->vendor_id == 0x03EB && dev->product_id == 0x2421)) {
gotDevice = true;
m_handlePath(dev->path);
//.........这里部分代码省略.........
示例6: file
Apsis::Registry::Scene::Scene(const char* path,
const Apsis::Engine::Object& loader) {
Json::Reader reader;
Json::Value value;
std::ifstream file(path);
reader.parse(file, value);
file.close();
if (value.isMember("type") &&
value["type"].compare(Json::Value("scene")) == 0) {
}
else {
throw "Scene file given is not of type 'scene'.";
}
if (value.isMember("inherit")) {
// TODO: inherit scenes
}
if (value.isMember("actors")) {
// Load actors
for (Json::Value::iterator it = value["actors"].begin();
it != value["actors"].end();
++it) {
if ((*it).isObject()) {
if ((*it).isMember("thing") &&
(*it).isMember("x") &&
(*it).isMember("y")) {
ActorInfo actor_info;
actor_info.thing = &loader.loadThing((*it)["thing"].asCString());
actor_info.x = (float)((*it)["x"].asDouble());
actor_info.y = (float)((*it)["y"].asDouble());
_actors.push_back(actor_info);
}
}
else {
throw "Scene file's 'actors' section is malformed.";
}
}
}
if (value.isMember("map")) {
// Just one map
if (value.isMember("maps")) {
// Error
throw "Scene file has both 'map' and 'maps' which is not allowed.";
}
MapInfo map_info;
if (value["map"].isString()) {
// x and y are 0
map_info.x = 0;
map_info.y = 0;
map_info.map = &loader.loadMap(value["map"].asCString());
}
else if (value["map"].isMember("map") &&
value["map"].isMember("x") &&
value["map"].isMember("y")) {
// x and y are given
map_info.x = (float)(value["map"]["x"].asDouble());
map_info.y = (float)(value["map"]["y"].asDouble());
map_info.map = &loader.loadMap(value["map"]["map"].asCString());
}
_maps.push_back(map_info);
}
else if (value.isMember("maps")) {
// More than one map
for (Json::Value::iterator it = value["maps"].begin();
it != value["maps"].end();
++it) {
if ((*it).isMember("map") &&
(*it).isMember("x") &&
(*it).isMember("y")) {
// x and y are given
MapInfo map_info;
map_info.x = (float)((*it)["x"].asDouble());
map_info.y = (float)((*it)["y"].asDouble());
map_info.map = &Apsis::World::Map::load((*it)["map"].asCString(),
loader);
_maps.push_back(map_info);
}
else {
throw "Scene file's 'maps' section is malformed.";
}
}
}
}
示例7: Parse
//{ paramList:[{"id":"参数id1","value":"新值1"},{"id":"参数id2","value":"新值2"}], "status":"成功、失败、取消等标识代码" }
BOOL CCxStructTreeRunResult::Parse( LPCTSTR lpszData, CCxStructTree * pTree )
{
Clear();
CString strSrc = lpszData == NULL ? "" : lpszData;
if (strSrc.IsEmpty()) return FALSE;
Json::Reader reader;
Json::Value obj, arrValue;
CCxStructTreeRunResultParam * pValue = NULL;
CCxStructTreeNode * pNode = NULL;
STRUCTTREEMAP_PARAM_VALUE::iterator itrExistNode;
CCxStructTreeRunResultParam * pExistValue = NULL;
CCxStructTreeRunResultComponent * pComponent = NULL;
CCxStructTreeRunResultFlow * pFlow = NULL;
CString str;
CDlgSvg* pSvg = GetSvgDilogPtr();
try
{
if (!reader.parse((char*)(LPCTSTR)strSrc, obj, false)) return FALSE;
if (!obj.isObject()) return FALSE;
m_strStatus = ( obj["status"].isString()) ? obj["status"].asCString() : _T("");
arrValue = obj["paramList"];
if ( !arrValue.isNull() && arrValue.isArray() )
{
for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
{
pValue = new CCxStructTreeRunResultParam();
pValue->m_strId = ( (*itr)["id"].isString()) ? (*itr)["id"].asCString() : _T("");
pValue->m_strValue = ( (*itr)["value"].isString()) ? (*itr)["value"].asCString() : _T("");
if ( pTree != NULL )
{
pNode = pTree->Find( pValue->m_strId );
if ( pNode == NULL )
{
::MessageBox( GetMainWnd(),"异常,返回的参数Id,在结构树中不存在", g_lpszAppTitle, MB_OK|MB_ICONERROR );
Clear();
return FALSE;
}
if ( !pNode->IsParamNode() )
{
::MessageBox( GetMainWnd(), "异常,返回的结果不是参数", g_lpszAppTitle, MB_OK|MB_ICONERROR );
Clear();
return FALSE;
}
pValue->m_pNode = (CCxStructTreeNodeParam *)pNode;
}
itrExistNode = m_mapRunReturn.find( pValue->m_strId );
if ( itrExistNode != m_mapRunReturn.end() )
{
pExistValue = itrExistNode->second;
m_mapRunReturn.erase( itrExistNode );
delete pExistValue;
pExistValue = NULL;
}
m_mapRunReturn.insert( make_pair( pValue->m_strId, pValue ) );
}
}
if ( !obj["flowIdList"].isNull() && obj["flowIdList"].isArray() )
{
arrValue = obj["flowIdList"];
for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
{
pFlow = new CCxStructTreeRunResultFlow();
str = ( (*itr)["id"].isString()) ? (*itr)["id"].asCString() : _T("");
if ( pSvg != NULL )
{
pFlow->m_strId = pSvg->JsMethod_ConvertFlowId( str );
}
pFlow->m_strStatus = ( (*itr)["status"].isString()) ? (*itr)["status"].asCString() : _T("");
if ( pTree != NULL )
{
pNode = pTree->Find( pFlow->m_strId );
if ( pNode == NULL )
{
::MessageBox(GetMainWnd(), "异常,返回的流程Id,在结构树中不存在", g_lpszAppTitle, MB_OK|MB_ICONERROR );
Clear();
return FALSE;
}
if ( !pNode->IsFlowNode() )
{
::MessageBox(GetMainWnd(), "异常,返回的流程Id与节点类型不匹配", g_lpszAppTitle, MB_OK|MB_ICONERROR );
Clear();
return FALSE;
}
pFlow->m_pNode = (CCxStructTreeNodeFlow *)pNode;
}
if ( find( m_vFlows.begin(), m_vFlows.end(), pFlow )
== m_vFlows.end() )
{
m_vFlows.push_back( pFlow );
}
}
}
if ( !obj["componentIdList"].isNull() && obj["componentIdList"].isArray() )
//.........这里部分代码省略.........
示例8: OnRecvCommand
void SnifferMain::OnRecvCommand(SnifferClient* client, const SCMD &scmd) {
switch(scmd.header.scmdt) {
case ExcuteCommand:{
// 执行Shell命令
string cmd = scmd.param;
string result = SystemComandExecuteWithResult(cmd);
FileLog(SnifferLogFileName, "SnifferMain::OnRecvCommand( 执行 : %s )", cmd.c_str());
FileLog(SnifferLogFileName, "SnifferMain::OnRecvCommand( 执行结果 : %s )", result.c_str());
// 返回命令结果
SCMD scmdSend;
scmdSend.header.scmdt = ExcuteCommandResult;
scmdSend.header.bNew = false;
scmdSend.header.seq = scmd.header.seq;
scmdSend.header.len = MIN(result.length(), MAX_PARAM_LEN - 1);
memcpy(scmdSend.param, result.c_str(), scmdSend.header.len);
scmdSend.param[scmdSend.header.len] = '\0';
client->SendCommand(scmdSend);
}break;
case SnifferListDir:{
// 列目录
Json::FastWriter writer;
Json::Value rootSend;
string result;
rootSend[COMMON_RET] = 0;
Json::Reader reader;
Json::Value rootRecv;
reader.parse(scmd.param, rootRecv);
int index = 0;
if( rootRecv[COMMON_PAGE_INDEX].isInt() ) {
index = rootRecv[COMMON_PAGE_INDEX].asInt();
}
int size = 0;
if( rootRecv[COMMON_PAGE_SIZE].isInt() ) {
size = rootRecv[COMMON_PAGE_SIZE].asInt();
}
string dir = "";
if( rootRecv[DIRECTORY].isString() ) {
dir = rootRecv[DIRECTORY].asString();
}
DIR *dirp;
dirent *dp;
int i = 0;
if( (dirp = opendir(dir.c_str())) != NULL ) {
rootSend[COMMON_RET] = 1;
int i = 0;
while( (dp = readdir(dirp)) != NULL ) {
Json::Value dirItem;
dirItem[D_TYPE] = dp->d_type;
if( dp->d_type == DT_DIR ) {
if( strcmp(dp->d_name, ".") != 0 ) {
if( i >= index * size && i < (index + 1) * size ) {
dirItem[D_NAME] = dp->d_name;
rootSend[FILE_LIST].append(dirItem);
}
i++;
}
} else {
if( i >= index * size && i < (index + 1) * size ) {
dirItem[D_NAME] = dp->d_name;
rootSend[FILE_LIST].append(dirItem);
}
i++;
}
}
closedir(dirp);
rootSend[COMMON_TOTAL] = i;
}
result = writer.write(rootSend);
SCMD scmdSend;
scmdSend.header.scmdt = SnifferTypeClientInfoResult;
scmdSend.header.bNew = false;
scmdSend.header.seq = scmd.header.seq;
scmdSend.header.len = MIN(result.length(), MAX_PARAM_LEN - 1);
memcpy(scmdSend.param, result.c_str(), scmdSend.header.len);
scmdSend.param[scmdSend.header.len] = '\0';
client->SendCommand(scmdSend);
}break;
case SinfferTypeStart:{
// 开始监听
FileLog(SnifferLogFileName, "SnifferMain::OnRecvCommand( 开始监听 )");
mSniffer.StartSniffer();
}break;
case SinfferTypeStop:{
//.........这里部分代码省略.........
示例9: handle
void UpdateUserData::handle(Manager* manager, SharedManager* sManager) {
bool validation = this->validateInput();
if(validation) {
struct mg_str *cl_header = mg_get_http_header(hm, "Token");
if(!cl_header) {
this->response(1, "Token Missing ", returnEmptyJsonObject());
return;
}
Json::Reader r = Json::Reader();
Json::Value value = Json::Value();
r.parse(hm->body.p, value);
// Local user update
User* user = manager->getUser(value.get("username","").asString());
if(!user) {
this->response(1, "User could not be modified", returnEmptyJsonObject());
return;
}
std::string token(getHeaderParam(cl_header->p));
if(token.compare(user->getToken()) != 0) {
this->response(2, "Invalid Token", returnEmptyJsonObject());
return;
}
user->updateWithJson(value);
bool updateUser = manager->updateUser(user);
if(updateUser) {
value["id"] = user->getId();
if(value.isMember("photoProfile") || value.isMember("photo_profile")) {
// Photo Profile Upload
std::string key = "";
value.isMember("photoProfile") ? key = "photoProfile" : key = "photo_profile";
Json::Value uploadP = Json::Value();
uploadP["photo"] = value.get(key, "").asString();
uploadP["id"] = user->getId();
value.removeMember(key);
int photoUp = sManager->putUserPhoto(uploadP);
if(!photoUp) {
this->response(1, "User photo profile could not be uploaded", returnEmptyJsonObject());
return;
}
}
// Rest of user data to update on Shared Server
// TODO: Falta subir los intereses nuevos que haya!
if(value.isMember("interests")) {
Json::Value interests = value.get("interests", Json::Value(Json::arrayValue));
Json::ValueConstIterator interestsIt = interests.begin();
while(interestsIt != interests.end()) {
Json::Value response = sManager->postInterest(*interestsIt);
// TODO: Alguna cola para reupload de intereses que debieron subir
// pero no pudieron por algun problema (que no sea duplicado)
interestsIt++;
}
}
if(value.isMember("edad")) value["age"] = value.get("edad", 18).asInt();
int sharedUpdate = sManager->putUser(value);
if(sharedUpdate) {
this->response(0, "Modified", user->getJson());
} else {
this->response(1, "User could not be modified", returnEmptyJsonObject());
}
} else {
this->response(1, "User could not be modified", returnEmptyJsonObject());
}
delete user;
}
}
示例10: handle_default
static int handle_default(struct mg_connection *conn, Settings& settings)
{
send_headers(conn);
if ( !settings.run_scripts.size() )
{
return send_error(conn, "Internal error: no scripts");
}
// hook up converter to engine
Engine engine(settings);
Converter converter(&engine, settings);
bool conversion_success = engine.run();
// collect info
QString result = engine.scriptResult();
double run_elapsedms = engine.runTime();
double convert_elapsedms = engine.convertTime();
QVector<QString> warnings = converter.warnings();
QVector<QString> errors = converter.errors();
debug_settings( settings, result, warnings, errors, conversion_success, run_elapsedms, convert_elapsedms );
// create json return
Json::Value root;
root["path"] = settings.out.toLocal8Bit().constData();
Json::Reader reader;
Json::Value result_root;
bool parsingSuccessful = false;
parsingSuccessful = reader.parse( result.toLocal8Bit().constData(), result_root );
if ( !parsingSuccessful )
{
result_root = Json::Value();
}
root["result"] = result_root;
root["conversion"] = conversion_success;
root["run_elapsed"] = run_elapsedms;
root["convert_elapsed"] = convert_elapsedms;
Json::Value js_warnings;
for( QVector<QString>::iterator it = warnings.begin();
it != warnings.end();
++it )
{
js_warnings.append( it->toLocal8Bit().constData() );
}
root["warnings"] = js_warnings;
Json::Value js_errors;
for( QVector<QString>::iterator it = errors.begin();
it != errors.end();
++it )
{
js_errors.append( it->toLocal8Bit().constData() );
}
root["errors"] = js_errors;
QFile* file = new QFile(settings.out);
file->open(QIODevice::ReadOnly);
QByteArray image = file->readAll();
int originalSize = image.length();
QString encoded = QString(image.toBase64());
int encodedSize = encoded.size();
root["image"] = encoded.toLocal8Bit().constData();
root["image_original_size"] = originalSize;
root["image_encoded_size"] = encodedSize;
root["image_format"] = settings.fmt.toLocal8Bit().constData();
Json::StyledWriter writer;
std::string json = writer.write(root);
mg_send_data(conn, json.c_str(), json.length());
if ( settings.statsd )
{
settings.statsd->inc(settings.statsd_ns + "request");
}
QString xtra = QString(LOG_STRING).arg(settings.in).arg(settings.screen_width).arg(settings.screen_height).arg(settings.out).arg(settings.fmt)
.arg(settings.selector.length()?settings.selector:"''")
.arg(settings.crop_rect.width()).arg(settings.crop_rect.height()).arg(settings.crop_rect.x()).arg(settings.crop_rect.y())
.arg(run_elapsedms).arg(convert_elapsedms);
log( conn, xtra.toLocal8Bit().constData() );
return MG_TRUE;
}
示例11: GetSerialAndToken
bool CICYThermostat::GetSerialAndToken()
{
std::stringstream sstr;
sstr << "username=" << m_UserName << "&password=" << m_Password;
std::string szPostdata=sstr.str();
std::vector<std::string> ExtraHeaders;
std::string sResult;
std::string sURL = "";
if ((m_companymode == CMODE_UNKNOWN) || (m_companymode == CMODE_PORTAL))
sURL = ICY_LOGIN_URL;
else if (m_companymode == CMODE_ENI)
sURL = ENI_LOGIN_URL;
else
sURL = SEC_LOGIN_URL;
if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult))
{
_log.Log(LOG_ERROR,"ICYThermostat: Error login!");
return false;
}
if (sResult.find("BadLogin") != std::string::npos)
{
if (m_companymode == CMODE_UNKNOWN)
{
//Try ENI mode
sURL = ENI_LOGIN_URL;
sResult = "";
if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult))
{
_log.Log(LOG_ERROR, "ICYThermostat: Error login!");
return false;
}
if (sResult.find("BadLogin") != std::string::npos)
{
if (m_companymode == CMODE_UNKNOWN)
{
//Try SEC mode
sURL = SEC_LOGIN_URL;
sResult = "";
if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult))
{
_log.Log(LOG_ERROR, "ICYThermostat: Error login!");
return false;
}
if (sResult.find("BadLogin") != std::string::npos)
{
_log.Log(LOG_ERROR, "ICYThermostat: Error login! (Check username/password)");
return false;
}
}
else
{
_log.Log(LOG_ERROR, "ICYThermostat: Error login! (Check username/password)");
return false;
}
}
}
else
{
_log.Log(LOG_ERROR, "ICYThermostat: Error login! (Check username/password)");
return false;
}
}
Json::Value root;
Json::Reader jReader;
bool ret = jReader.parse(sResult, root);
if (!ret)
{
_log.Log(LOG_ERROR, "ICYThermostat: Invalid data received, or invalid username/password!");
return false;
}
if (root["serialthermostat1"].empty() == true)
{
_log.Log(LOG_ERROR, "ICYThermostat: Invalid data received, or invalid username/password!");
return false;
}
m_SerialNumber = root["serialthermostat1"].asString();
if (root["token"].empty() == true)
{
_log.Log(LOG_ERROR, "ICYThermostat: Invalid data received, or invalid username/password!");
return false;
}
m_Token = root["token"].asString();
if (m_companymode == CMODE_UNKNOWN)
{
if (sURL == ICY_LOGIN_URL)
m_companymode = CMODE_PORTAL;
else if (sURL == ENI_LOGIN_URL)
m_companymode = CMODE_ENI;
else
m_companymode = CMODE_SEC;
}
return true;
}
示例12: main
int main ()
{
int connectionFd, rc, index = 0, limit = MAX_BUFFER;
struct sockaddr_in servAddr, localAddr;
char buffer[MAX_BUFFER+1];
#ifdef WIN32
// Start up WinSock2
WSADATA wsaData;
if( WSAStartup( WINSOCKVERSION, &wsaData) != 0 )
return ERROR;
#endif
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(PORT);
servAddr.sin_addr.s_addr = inet_addr(HOST);
// Create socket
connectionFd = socket(AF_INET, SOCK_STREAM, 0);
/* bind any port number */
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(0);
rc = bind(connectionFd,
(struct sockaddr *) &localAddr, sizeof(localAddr));
// Connect to Server
connect(connectionFd,
(struct sockaddr *)&servAddr, sizeof(servAddr));
// Send request to Server
sprintf( buffer, "%s", "{\"robo1\":{\"x\":1,\"y\":2}, \"robo2\":{\"x\":3,\"y\":4}}" );
send( connectionFd, buffer, strlen(buffer), 0 );
printf("Client sent to sever %s\n", buffer);
// Receive data from Server
sprintf( buffer, "%s", "" );
recv(connectionFd, buffer, MAX_BUFFER, 0);
std::string strJson = buffer;
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(strJson.c_str(), root);
if(!parsingSuccessful){
std::cout<<"Failed to parse"<<std::endl;
}
std::cout<<"Object json - "<<root.get("robo1","A Default Value if not exists")<<std::endl;
printf("Client read from Server %s\n", buffer);
#ifdef WIN32
closesocket(connectionFd);
#else
close(connectionFd);
#endif
printf("Client closed.\n");
return(0);
}
示例13: string
CScalePredictor::CScalePredictor(string filename) {
if (filename.compare("none") ==0) {
return;
}
string contents = get_file_contents(filename);
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(contents, root);
if (!parsingSuccessful) {
std::cout << "Failed to parse \n" << reader.getFormatedErrorMessages()<< endl;
}
// Get the input scaler
this->InputScaler = parse_cscaler(root["InputScaler"]);
this->OutputScaler = parse_cscaler(root["OutputScaler"]);
this->Pred = parse_predictor(root["Predictor"]);
// Check the predictions
int nTestInputs = root["TestInputs"].size();
int nTestOutputs = root["TestOutputs"].size();
if (nTestInputs != nTestOutputs) {
cout << "Number of test inputs and number of test outputs doesn't match" << endl;
}
Json::Value testInputs = root["TestInputs"];
Json::Value testOutputs = root["TestOutputs"];
for (int i = 0; i < nTestInputs; i++) {
int nInputs = testInputs[i].size();
int nOutputs = testOutputs[i].size();
double *input = new double[nInputs];
double *output = new double[nOutputs];
for (int j = 0; j < nInputs; j++) {
input[j] = testInputs[i][j].asDouble();
}
for (int j=0; j < nOutputs; j++) {
output[j] = testOutputs[i][j].asDouble();
}
double *predOutput = new double[nOutputs];
this->Predict(input, predOutput);
bool mismatch = 0;
for (int j = 0; j < nOutputs; j++) {
double max = abs(output[j]);
if (predOutput[j] > max) {
max = abs(predOutput[j]);
}
if (max < 1.0) {
max = 1.0;
}
if (abs(output[j] - predOutput[j])/(max) > 1e-12) {
mismatch = 1;
}
cout.precision(16);
if (mismatch) {
cout << "Prediction mismatch" << endl;
for (int j = 0; j < nOutputs; j++) {
cout << "j = " << " true: " << output[j] << " pred: " << predOutput[j] << " rel error: " << abs(output[j] - predOutput[j])/(max) << endl;
}
throw string("mismatch");
}
}
// if (mismatch) {
// throw(-1);
// }
delete [] predOutput;
delete [] input;
delete [] output;
}
return;
}
示例14: parse_docker
bool sinsp_container_manager::parse_docker(sinsp_container_info* container)
{
string file = string(scap_get_host_root()) + "/var/run/docker.sock";
int sock = socket(PF_UNIX, SOCK_STREAM, 0);
if(sock < 0)
{
ASSERT(false);
return false;
}
struct sockaddr_un address;
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
strncpy(address.sun_path, file.c_str(), sizeof(address.sun_path) - 1);
address.sun_path[sizeof(address.sun_path) - 1]= '\0';
if(connect(sock, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0)
{
return false;
}
string message = "GET /containers/" + container->m_id + "/json HTTP/1.0\r\n\n";
if(write(sock, message.c_str(), message.length()) != (ssize_t) message.length())
{
ASSERT(false);
close(sock);
return false;
}
char buf[256];
string json;
ssize_t res;
while((res = read(sock, buf, sizeof(buf))) != 0)
{
if(res == -1)
{
ASSERT(false);
close(sock);
return false;
}
buf[res] = 0;
json += buf;
}
close(sock);
size_t pos = json.find("{");
if(pos == string::npos)
{
ASSERT(false);
return false;
}
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(json.substr(pos), root);
if(!parsingSuccessful)
{
ASSERT(false);
return false;
}
container->m_image = root["Config"]["Image"].asString();
container->m_name = root["Name"].asString();
if(!container->m_name.empty())
{
container->m_name = container->m_name.substr(1);
}
string ip = root["NetworkSettings"]["IPAddress"].asString();
if(inet_pton(AF_INET, ip.c_str(), &container->m_container_ip) == -1)
{
ASSERT(false);
}
container->m_container_ip = ntohl(container->m_container_ip);
vector<string> ports = root["NetworkSettings"]["Ports"].getMemberNames();
for(vector<string>::const_iterator it = ports.begin(); it != ports.end(); ++it)
{
size_t tcp_pos = it->find("/tcp");
if(tcp_pos == string::npos)
{
continue;
}
uint16_t container_port = atoi(it->c_str());
Json::Value& v = root["NetworkSettings"]["Ports"][*it];
if(v.isArray())
{
for(uint32_t j = 0; j < v.size(); ++j)
{
sinsp_container_info::container_port_mapping port_mapping;
ip = v[j]["HostIp"].asString();
string port = v[j]["HostPort"].asString();
//.........这里部分代码省略.........
示例15: SwitchLight
bool CPhilipsHue::SwitchLight(const int nodeID, const std::string &LCmd, const int svalue)
{
std::vector<std::string> ExtraHeaders;
std::string sResult;
std::stringstream sPostData;
if (LCmd=="On")
{
sPostData << "{\"on\": true }";
}
else if (LCmd == "Off")
{
sPostData << "{\"on\": false }";
}
else if (LCmd == "Set Level")
{
sPostData << "{\"on\": true, \"bri\": " << svalue << " }";
}
else if (LCmd == "Set White")
{
sPostData << "{\"on\": true, \"sat\": 0 , \"bri\": 255, \"hue\": 0 }";
}
else if (LCmd == "Set Hue")
{
sPostData << "{\"on\": true, \"sat\": 255 , \"hue\": " << svalue << " }";
}
else
{
_log.Log(LOG_ERROR, "Philips Hue: Invalid light command received!");
return false;
}
std::stringstream sstr2;
sstr2 << "http://" << m_IPAddress
<< ":" << m_Port
<< "/api/" << m_UserName
<< "/lights/" << nodeID << "/state";
std::string sURL = sstr2.str();
if (!HTTPClient::PUT(sURL, sPostData.str(), ExtraHeaders, sResult))
{
_log.Log(LOG_ERROR, "Philips Hue: Error connecting to Hue bridge, (Check IPAddress/Username)");
return false;
}
Json::Value root;
Json::Reader jReader;
bool ret = jReader.parse(sResult, root);
if (!ret)
{
_log.Log(LOG_ERROR, "Philips Hue: Invalid data received, or invalid IPAddress/Username!");
return false;
}
if (sResult.find("error") != std::string::npos)
{
//We had an error
_log.Log(LOG_ERROR, "Philips Hue: Error received: %s", root[0]["error"]["description"].asString().c_str());
return false;
}
return true;
}