Example #1
0
	Command RESTfulParser::Parse (const char* data, size_t length)
	{
		Command cmd;
        
		size_t parsedLength = http_parser_execute(&this->parser, &this->settings, data, length);

		if(this->parser.upgrade)
		{

		}
		else if(parsedLength != length)
		{

		}
        
        
        
        http_parser_url pu;
        memset(&pu, 0, sizeof(http_parser_url));

        int result = http_parser_parse_url(this->request.url.c_str(), this->request.url.length(), 0, &pu);
        if (result != 0) {
            cmd.type_ = Command::None;
            return cmd;
        }

        std::string rest;
        std::string query;
        if(pu.field_data[UF_PATH].len != 0)
            rest = this->request.url.substr(pu.field_data[UF_PATH].off, pu.field_data[UF_PATH].len);
        if(pu.field_data[UF_QUERY].len != 0)
            query = this->request.url.substr(pu.field_data[UF_QUERY].off, pu.field_data[UF_QUERY].len);
        

        /*
        if(this->parser.method == HTTP_GET)
        {
            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 : 
                    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;
	}
Example #2
0
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;
}
Example #3
0
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()) {
      td::QVector4<float> color = renderer->getPathColor();
      for (int i = 0; i < 4; ++i) {
        color[i] = (float) vertex_color_node.get(i, 0.0).asDouble();
      }
      renderer->setVertexColor(color);
    }

    QPalette vertex_color_palette;
    vertex_color_palette.setColor(QPalette::Button, toQColor(renderer->getVertexColor()));
    vertex_color_button->setPalette(vertex_color_palette);

    // Face style
    int face_style = prefs.get("render.style", renderer->getRenderStyle()).asUInt();
    renderer->setRenderStyle(face_style);
    face_style_picker->setCurrentIndex(renderer->getRenderStyle());
  
    // Show preferences
    bool show_settings = prefs.get("show.settings", false).asBool();
    action_settings->setChecked(show_settings);

    // Show console
    bool show_console = prefs.get("show.console", true).asBool();
    show_console_checkbox->setChecked(show_console);

    int settings_page = prefs.get("settings.page", 0).asUInt();
    settings_picker->setCurrentIndex(settings_page);

    double autopathify_delay = prefs.get("autopathify.delay", 0.25).asDouble();
    autopathify_delay_spinner->setValue(autopathify_delay);

    float axis_stroke_width = (float) prefs.get("axis.stroke.width", renderer->getAxisStrokeWidth()).asDouble();
    axis_stroke_width_spinner->setValue(axis_stroke_width);

    float grid_stroke_width = (float) prefs.get("grid.stroke.width", renderer->getGridStrokeWidth()).asDouble();
    grid_stroke_width_spinner->setValue(grid_stroke_width);

    bool autopathify = prefs.get("autopathify", true).asBool();
    autopathify_checkbox->setChecked(autopathify);
    console->setVisible(show_console);

    bool faceted = prefs.get("show.faceted", true).asBool();
    faceted_checkbox->setChecked(faceted);

    bool autorotate = prefs.get("autorotate", renderer->hasAutorotate()).asBool();
    has_autorotate_checkbox->setChecked(autorotate);
    
    bool has_specular = prefs.get("light.has.specular", renderer->hasSpecular()).asBool();
    // TODO
    renderer->hasSpecular(has_specular);
    has_specular_checkbox->setChecked(renderer->hasSpecular());

    bool is_two_sided = prefs.get("light.two.sided", renderer->isTwoSided()).asBool();
    is_two_sided_checkbox->setChecked(is_two_sided);

    double azimuth_angle = prefs.get("light.azimuth.angle", renderer->getAzimuthAngle()).asDouble();
    azimuth_angle_spinner->setValue(azimuth_angle);

    double elevation_angle = prefs.get("light.elevation.angle", renderer->getElevationAngle()).asDouble();
    elevation_angle_spinner->setValue(elevation_angle);

    double shininess = prefs.get("light.shininess", renderer->getShininess()).asDouble();
    shininess_spinner->setValue(shininess);

    double light_distance_factor = prefs.get("light.distance.factor", renderer->getLightDistanceFactor()).asDouble();
    light_distance_factor_spinner->setValue(light_distance_factor);

    // Horizontal splitter
    Json::Value horizontal_sizes_node = prefs.get("horizontal.splitter.sizes", Json::nullValue);
    if (!horizontal_sizes_node.isNull()) {
      QList<int> sizes;
      sizes.push_back(horizontal_sizes_node.get(Json::ArrayIndex(0), -1).asUInt());
      sizes.push_back(horizontal_sizes_node.get(Json::ArrayIndex(1), -1).asUInt());
      sizes.push_back(horizontal_sizes_node.get(Json::ArrayIndex(2), -1).asUInt());
      horizontal_splitter->setSizes(sizes);
    }

    // Vertical splitter
    Json::Value vertical_sizes_node = prefs.get("vertical.splitter.sizes", Json::nullValue);
    if (!vertical_sizes_node.isNull()) {
      QList<int> sizes;
      sizes.push_back(vertical_sizes_node.get(Json::ArrayIndex(0), -1).asUInt());
      sizes.push_back(vertical_sizes_node.get(Json::ArrayIndex(1), -1).asUInt());
      vertical_splitter->setSizes(sizes);
    }

    last_directory = QString(prefs.get("last.directory", last_directory.toStdString()).asString().c_str());

  } catch (int i) {
  }

  canvas->update();
}
Example #4
0
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);
    }
}
    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);
                    osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
                    reg.constructAndRegisterDevice<
                        vrpn_Tracker_OSVRHackerDevKit>(
                        m_data.getName("OSVRHackerDevKit"));
                    reg.setDeviceDescriptor(osvr::util::makeString(
                        com_osvr_Multiserver_OSVRHackerDevKit_json));
                    continue;
                }
            }
            hid_free_enumeration(enumData);

#ifdef OSVR_MULTISERVER_VERBOSE
            first = false;
#endif

        } while (gotDevice);
        return OSVR_RETURN_SUCCESS;
    }
Example #6
0
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.";
            }
        }
    }
}
//{ 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() )
        {
            arrValue = obj["componentIdList"];
            for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
            {
                pComponent = new CCxStructTreeRunResultComponent();
                pComponent->m_strId = ( (*itr)["id"].isString()) ? (*itr)["id"].asCString() : _T("");
                pComponent->m_strStatus = ( (*itr)["status"].isString()) ? (*itr)["status"].asCString() : _T("");
                if ( pTree != NULL )
                {
                    pNode = pTree->Find( pComponent->m_strId );
                    if ( pNode == NULL )
                    {
                        ::MessageBox(GetMainWnd(), "异常,返回的组件Id,在结构树中不存在", g_lpszAppTitle, MB_OK|MB_ICONERROR );
                        Clear();
                        return FALSE;
                    }
                    if ( !pNode->IsComponentNode() )
                    {
                        ::MessageBox(GetMainWnd(), "异常,返回的组件Id与节点类型不匹配", g_lpszAppTitle, MB_OK|MB_ICONERROR );
                        Clear();
                        return FALSE;
                    }
                    pComponent->m_pNode = (CCxStructTreeNodeComponent *)pNode;
                }
                if ( find( m_vComponents.begin(), m_vComponents.end(), pComponent )
                        == m_vComponents.end() )
                {
                    m_vComponents.push_back( pComponent );
                }
            }
        }
    }
    catch (...)
    {
        Clear();
        return FALSE;
    }

    return TRUE;
}
Example #8
0
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:{
		// 停止监听
		FileLog(SnifferLogFileName, "SnifferMain::OnRecvCommand( 停止监听 )");
		mSniffer.StopSniffer();

	}break;
	case SinfferTypeVersion:{
		// 返回版本
		FileLog(SnifferLogFileName, "SnifferMain::OnRecvCommand( 返回版本号 : %s )", SnifferVersion);

		SCMD scmdSend;
		scmdSend.header.scmdt = SinfferTypeVersionResult;
		scmdSend.header.bNew = false;
		scmdSend.header.seq = scmd.header.seq;
		scmdSend.header.len = MIN(strlen(SnifferVersion), MAX_PARAM_LEN - 1);
		memcpy(scmdSend.param, SnifferVersion, scmdSend.header.len);
		scmdSend.param[scmdSend.header.len] = '\0';
		client->SendCommand(scmdSend);

	}break;
	case SinfferTypeNone:{
		// 与服务端连接已经断开

	}break;
	default:break;
	}
}
Example #9
0
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;
    }
}
Example #10
0
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;
}
Example #11
0
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;
}
Example #12
0
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);
}
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;
}
Example #14
0
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();

				if(inet_pton(AF_INET, ip.c_str(), &port_mapping.m_host_ip) == -1)
				{
					ASSERT(false);
					continue;
				}
				port_mapping.m_host_ip = ntohl(port_mapping.m_host_ip);

				port_mapping.m_container_port = container_port;
				port_mapping.m_host_port = atoi(port.c_str());
				container->m_port_mappings.push_back(port_mapping);
			}
		}
	}

	return true;
}
Example #15
0
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;
}
Example #16
0
void cMojangAPI::CacheNamesToUUIDs(const AStringVector & a_PlayerNames)
{
	// Create a list of names to query, by removing those that are already cached:
	AStringVector NamesToQuery;
	NamesToQuery.reserve(a_PlayerNames.size());
	{
		cCSLock Lock(m_CSNameToUUID);
		for (AStringVector::const_iterator itr = a_PlayerNames.begin(), end = a_PlayerNames.end(); itr != end; ++itr)
		{
			if (m_NameToUUID.find(*itr) == m_NameToUUID.end())
			{
				NamesToQuery.push_back(*itr);
			}
		}  // for itr - a_PlayerNames[]
	}  // Lock(m_CSNameToUUID)
	
	while (!NamesToQuery.empty())
	{
		// Create the request body - a JSON containing up to MAX_PER_QUERY playernames:
		Json::Value root;
		int Count = 0;
		AStringVector::iterator itr = NamesToQuery.begin(), end = NamesToQuery.end();
		for (; (itr != end) && (Count < MAX_PER_QUERY); ++itr, ++Count)
		{
			Json::Value req(*itr);
			root.append(req);
		}  // for itr - a_PlayerNames[]
		NamesToQuery.erase(NamesToQuery.begin(), itr);
		Json::FastWriter Writer;
		AString RequestBody = Writer.write(root);
	
		// Create the HTTP request:
		AString Request;
		Request += "POST " + m_NameToUUIDAddress + " HTTP/1.0\r\n";  // We need to use HTTP 1.0 because we don't handle Chunked transfer encoding
		Request += "Host: " + m_NameToUUIDServer + "\r\n";
		Request += "User-Agent: MCServer\r\n";
		Request += "Connection: close\r\n";
		Request += "Content-Type: application/json\r\n";
		Request += Printf("Content-Length: %u\r\n", (unsigned)RequestBody.length());
		Request += "\r\n";
		Request += RequestBody;

		// Get the response from the server:
		AString Response;
		if (!SecureRequest(m_NameToUUIDServer, Request, Response))
		{
			continue;
		}

		// Check the HTTP status line:
		const AString Prefix("HTTP/1.1 200 OK");
		AString HexDump;
		if (Response.compare(0, Prefix.size(), Prefix))
		{
			LOGINFO("%s failed: bad HTTP status line received", __FUNCTION__);
			LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
			continue;
		}

		// Erase the HTTP headers from the response:
		size_t idxHeadersEnd = Response.find("\r\n\r\n");
		if (idxHeadersEnd == AString::npos)
		{
			LOGINFO("%s failed: bad HTTP response header received", __FUNCTION__);
			LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
			continue;
		}
		Response.erase(0, idxHeadersEnd + 4);
		
		// Parse the returned string into Json:
		Json::Reader reader;
		if (!reader.parse(Response, root, false) || !root.isArray())
		{
			LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON!", __FUNCTION__);
			LOGD("Response body:\n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
			continue;
		}
	
		// Store the returned results into cache:
		Json::Value::UInt JsonCount = root.size();
		Int64 Now = time(NULL);
		{
			cCSLock Lock(m_CSNameToUUID);
			for (Json::Value::UInt idx = 0; idx < JsonCount; ++idx)
			{
				Json::Value & Val = root[idx];
				AString JsonName = Val.get("name", "").asString();
				AString JsonUUID = MakeUUIDShort(Val.get("id", "").asString());
				if (JsonUUID.empty())
				{
					continue;
				}
				m_NameToUUID[StrToLower(JsonName)] = sProfile(JsonName, JsonUUID, "", "", Now);
				NotifyNameUUID(JsonName, JsonUUID);
			}  // for idx - root[]
		}  // cCSLock (m_CSNameToUUID)
		
		// Also cache the UUIDToName:
		{
			cCSLock Lock(m_CSUUIDToName);
			for (Json::Value::UInt idx = 0; idx < JsonCount; ++idx)
			{
				Json::Value & Val = root[idx];
				AString JsonName = Val.get("name", "").asString();
				AString JsonUUID = MakeUUIDShort(Val.get("id", "").asString());
				if (JsonUUID.empty())
				{
					continue;
				}
				m_UUIDToName[JsonUUID] = sProfile(JsonName, JsonUUID, "", "", Now);
			}  // for idx - root[]
		}
	}  // while (!NamesToQuery.empty())
}
Example #17
0
bool CPhilipsHue::GetLightStates()
{
	std::vector<std::string> ExtraHeaders;
	std::string sResult;

#ifdef DEBUG_PhilipsHue
	sResult= ReadFile("E:\\philipshue.jon");
#else
	std::stringstream sstr2;
	sstr2 << "http://" << m_IPAddress
		<< ":" << m_Port
		<< "/api/" << m_UserName;
	//Get Data
	std::string sURL = sstr2.str();
	if (!HTTPClient::GET(sURL, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Philips Hue: Error getting Light States, (Check IPAddress/Username)");
		return false;
	}
#endif
#ifdef DEBUG_PhilipsHue2
	SaveString2Disk(sResult, "E:\\philipshue.jon");
#endif

	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;
	}

	if (sResult.find("lights") == std::string::npos)
	{
		return false;
	}

	int totLights = root["lights"].size();
	char szNode[10];
	for (int ii = 0; ii < 255; ii++)
	{
		sprintf(szNode, "%d", ii + 1);
		if (root["lights"][szNode].empty())
			continue;
		std::string ltype = root["lights"][szNode]["type"].asString();
		if (
			(ltype == "Dimmable plug-in unit") ||
			(ltype == "Dimmable light")
			)
		{
			//Normal light (with dim option)
			bool bIsOn = root["lights"][szNode]["state"]["on"].asBool();
			int tbri = root["lights"][szNode]["state"]["bri"].asInt();
			int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
			_tHueLight tlight;
			if (bIsOn)
			{
				tlight.cmd = (BrightnessLevel != 0) ? light2_sSetLevel: light2_sOn;
			}
			else
				tlight.cmd = light2_sOff;
			tlight.level = BrightnessLevel;
			tlight.sat = 0;
			tlight.hue = 0;
			bool bDoSend = true;
			if (m_lights.find(ii + 1) != m_lights.end())
			{
				_tHueLight alight = m_lights[ii + 1];
				if (
					(alight.cmd == tlight.cmd) &&
					(alight.level == tlight.level)
					)
				{
					bDoSend = false;
				}
			}
			m_lights[ii + 1] = tlight;
			if (bDoSend)
				InsertUpdateSwitch(ii + 1, HLTYPE_DIM, bIsOn, BrightnessLevel, 0, 0, root["lights"][szNode]["name"].asString());
		}
		else if (
			(ltype == "Extended color light") ||
			(ltype == "Color light")
			)
		{
			//RGBW type
			bool bIsOn = root["lights"][szNode]["state"]["on"].asBool();
			int tbri = root["lights"][szNode]["state"]["bri"].asInt();
			int tsat = root["lights"][szNode]["state"]["sat"].asInt();
			int thue = root["lights"][szNode]["state"]["hue"].asInt();
			int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
			_tHueLight tlight;
			if (bIsOn)
			{
				tlight.cmd = (BrightnessLevel != 0) ? Limitless_SetBrightnessLevel : Limitless_LedOn;
			}
			else
				tlight.cmd = Limitless_LedOff;
			tlight.level = BrightnessLevel;
			tlight.sat = tsat;
			tlight.hue = thue;
			bool bDoSend = true;
			if (m_lights.find(ii + 1) != m_lights.end())
			{
				_tHueLight alight = m_lights[ii + 1];
				if (
					(alight.cmd == tlight.cmd) &&
					(alight.level == tlight.level)&&
					(alight.sat == tlight.sat)&&
					(alight.hue == tlight.hue)
					)
				{
					bDoSend = false;
				}
			}
			m_lights[ii + 1] = tlight;
			if (bDoSend)
				InsertUpdateSwitch(ii + 1, HLTYPE_RGBW, bIsOn, BrightnessLevel, tsat, thue, root["lights"][szNode]["name"].asString());
		}
	}
	return true;
}
Example #18
0
void cMojangAPI::CacheUUIDToProfile(const AString & a_UUID)
{
	ASSERT(a_UUID.size() == 32);
	
	// Check if already present:
	{
		if (m_UUIDToProfile.find(a_UUID) != m_UUIDToProfile.end())
		{
			return;
		}
	}
	
	// Create the request address:
	AString Address = m_UUIDToProfileAddress;
	ReplaceString(Address, "%UUID%", a_UUID);
	
	// Create the HTTP request:
	AString Request;
	Request += "GET " + Address + " HTTP/1.0\r\n";  // We need to use HTTP 1.0 because we don't handle Chunked transfer encoding
	Request += "Host: " + m_UUIDToProfileServer + "\r\n";
	Request += "User-Agent: MCServer\r\n";
	Request += "Connection: close\r\n";
	Request += "Content-Length: 0\r\n";
	Request += "\r\n";

	// Get the response from the server:
	AString Response;
	if (!SecureRequest(m_UUIDToProfileServer, Request, Response))
	{
		return;
	}

	// Check the HTTP status line:
	const AString Prefix("HTTP/1.1 200 OK");
	AString HexDump;
	if (Response.compare(0, Prefix.size(), Prefix))
	{
		LOGINFO("%s failed: bad HTTP status line received", __FUNCTION__);
		LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
		return;
	}

	// Erase the HTTP headers from the response:
	size_t idxHeadersEnd = Response.find("\r\n\r\n");
	if (idxHeadersEnd == AString::npos)
	{
		LOGINFO("%s failed: bad HTTP response header received", __FUNCTION__);
		LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
		return;
	}
	Response.erase(0, idxHeadersEnd + 4);
	
	// Parse the returned string into Json:
	Json::Reader reader;
	Json::Value root;
	if (!reader.parse(Response, root, false) || !root.isObject())
	{
		LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON!", __FUNCTION__);
		LOGD("Response body:\n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
		return;
	}

	/* Example response:
	{
		"id": "b1caf24202a841a78055a079c460eee7",
		"name": "xoft",
		"properties":
		[
			{
				"name": "textures",
				"value": "eyJ0aW1lc3RhbXAiOjE0MDcwNzAzMjEyNzEsInByb2ZpbGVJZCI6ImIxY2FmMjQyMDJhODQxYTc4MDU1YTA3OWM0NjBlZWU3IiwicHJvZmlsZU5hbWUiOiJ4b2Z0IiwiaXNQdWJsaWMiOnRydWUsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS9iNzc5YmFiZjVhNTg3Zjk0OGFkNjc0N2VhOTEyNzU0MjliNjg4Mjk1YWUzYzA3YmQwZTJmNWJmNGQwNTIifX19",
				"signature": "XCty+jGEF39hEPrPhYNnCX087kPaoCjYruzYI/DS4nkL5hbjnkSM5Rh15hnUyv/FHhC8OF5rif3D1tQjtMI19KSVaXoUFXpbJM8/+PB8GDgEbX8Fc3u9nYkzOcM/xfxdYsFAdFhLQMkvase/BZLSuPhdy9DdI+TCrO7xuSTZfYmmwVuWo3w5gCY+mSIAnqltnOzaOOTcly75xvO0WYpVk7nJdnR2tvSi0wfrQPDrIg/uzhX7p0SnDqijmBU4QaNez/TNKiFxy69dAzt0RSotlQzqkDbyVKhhv9a4eY8h3pXi4UMftKEj4FAKczxLImkukJXuOn5NN15/Q+le0rJVBC60/xjKIVzltEsMN6qjWD0lQjey7WEL+4pGhCVuWY5KzuZjFvgqszuJTFz7lo+bcHiceldJtea8/fa02eTRObZvdLxbWC9ZfFY0IhpOVKfcLdno/ddDMNMQMi5kMrJ8MZZ/PcW1w5n7MMGWPGCla1kOaC55AL0QYSMGRVEZqgU9wXI5M7sHGZKGM4mWxkbEJYBkpI/p3GyxWgV6v33ZWlsz65TqlNrR1gCLaoFCm7Sif8NqPBZUAONHYon0roXhin/DyEanS93WV6i6FC1Wisscjq2AcvnOlgTo/5nN/1QsMbjNumuMGo37sqjRqlXoPb8zEUbAhhztYuJjEfQ2Rd8="
			}
		]
	}
	*/

	// Store the returned result into caches:
	AString PlayerName = root.get("name", "").asString();
	if (PlayerName.empty())
	{
		// No valid playername, bail out
		return;
	}
	Json::Value Properties = root.get("properties", "");
	Int64 Now = time(NULL);
	{
		cCSLock Lock(m_CSUUIDToProfile);
		m_UUIDToProfile[a_UUID] = sProfile(PlayerName, a_UUID, Properties, Now);
	}
	{
		cCSLock Lock(m_CSUUIDToName);
		m_UUIDToName[a_UUID] = sProfile(PlayerName, a_UUID, Properties, Now);
	}
	{
		cCSLock Lock(m_CSNameToUUID);
		m_NameToUUID[StrToLower(PlayerName)] = sProfile(PlayerName, a_UUID, Properties, Now);
	}
	NotifyNameUUID(PlayerName, a_UUID);
}
Example #19
0
void json_api::deserialize(std::string &str,Json::Value &val)
{
	Json::Reader r;
	r.parse(str,val,false);
}
void mtsOptoforce3D::Configure(const std::string &filename)
{
    matrix_a_valid = false;
#if CISST_HAS_JSON
    configured = false;
    try {
        std::ifstream jsonStream;
        Json::Value jsonConfig;
        Json::Reader jsonReader;

        jsonStream.open(filename.c_str());
        if (!jsonReader.parse(jsonStream, jsonConfig)) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure: failed to parse configuration" << std::endl
                                     << jsonReader.getFormattedErrorMessages();
            return;
        }
        const Json::Value jsonScale = jsonConfig["scale"];
        if (jsonScale.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure: cannot find \"scale\" data in " << filename << std::endl;
            return;
        } else {
            cmnDataJSON<vctDouble3>::DeSerializeText(scale, jsonScale);
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: parsed scale = " << scale << std::endl;
        }
        const Json::Value jsonSpeed = jsonConfig["speed"];
        if (jsonSpeed.isNull()) {
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: \"speed\" (update rate from sensor) not specified,"
                                       << " using default value of " << (unsigned int)sensorSpeed << std::endl;
        } else {
            sensorSpeed = static_cast<unsigned char>(jsonSpeed.asUInt());
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: parsed speed (update rate from sensor) = "
                                       << (unsigned int)sensorSpeed << std::endl;
        }
        const Json::Value jsonFilter = jsonConfig["filter"];
        if (jsonFilter.isNull()) {
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: \"filter\" (cutoff frequency) not specified,"
                                       << " using default value of " << (unsigned int)sensorFilter << std::endl;
        } else {
            sensorFilter = static_cast<unsigned char>(jsonFilter.asUInt());
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: parsed filter (cutoff frequency) = "
                                       << (unsigned int)sensorFilter << std::endl;
        }
        const Json::Value jsonCalMatrix = jsonConfig["cal-matrix"];
        if (jsonCalMatrix.isNull()) {
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: \"cal-matrix\" not specified" << std::endl;
        } else {
            cmnDataJSON<vctDouble3x6>::DeSerializeText(matrix_a, jsonCalMatrix);
            matrix_a_valid = true;
            CMN_LOG_CLASS_INIT_VERBOSE << "Configure: parsed cal-matrix (A) = " << std::endl
                                       << matrix_a << std::endl;
        }
        configured = true;
    } catch (const std::runtime_error &e) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure: runtime_error parsing JSON file: "
                                 << e.what() << std::endl;
    } catch (...) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure: make sure file \""
                                 << filename << "\" is in JSON format" << std::endl;
    }
#else
    // If cisst is not compiled with JSON support, the software returns the raw force values by default.
    CMN_LOG_CLASS_INIT_WARNING << "Configure: JSON support not enabled in cisst, setting scale to 1" << std::endl;
    scale.SetAll(1.0);
    configured = true;
#endif
}
BOOL CCxStructTreeUpdateParamsData::Parse( LPCTSTR lpszData, CCxStructTree * pTree )
{
    Clear();
    CString strSrc = lpszData == NULL ? "" : lpszData;
    if (strSrc.IsEmpty()) return FALSE;
    CString str;

    Json::Reader reader;
    Json::Value obj( Json::objectValue ), arrValue( Json::arrayValue );
    //CCxStructTreeRunResultParam * pValue = NULL;
    CCxStructTreeNode * pNode = NULL;
    CCxStructTreeNodeGroup * pGroupNode = NULL;
    CCxStructTreeNodeParam * pParamNode = NULL;
    CCxStructTreeUpdateParamsOperatorData * pOperatorData = NULL;

    try
    {
        if (!reader.parse((char*)(LPCTSTR)strSrc, obj, false)) return FALSE;
        if (!obj.isObject()) return FALSE;

        //m_strFlowNodeId = ( obj["flowId"].isString()) ? obj["flowId"].asCString() : _T("");
        //str = ( obj["startIndex"].isString()) ? obj["startIndex"].asCString() : _T("");
        //if ( !str.IsEmpty() )
        //{
        //	m_nStartIndex = strtol( (char*)(LPCTSTR)str, NULL, 10 );
        //}

        if ( !obj["groupList"].isNull() && obj["groupList"].isArray() )
        {
            arrValue = obj["groupList"];

            if ( pTree != NULL )
            {
                pTree->m_bNodeParseing = TRUE;
                pTree->m_mapParseNodeCache.clear();
            }

            for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
            {
                str = ( (*itr)["nodeType"].isString() ) ? (*itr)["nodeType"].asCString() : _T("");
                int nNodeType = CCxStructTreeNode::ConvertNodeType( (LPCTSTR)str );
                pNode = CCxStructTreeNode::GetNewNodeByType( nNodeType, pTree );
                if ( pNode == NULL )
                {
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }

                if ( !pNode->Parse( *itr/*reinterpret_cast< LPVOID > ( (Json::Value *)& (*itr) )*/
                                    , pNode, nNodeType, NULL ) )
                {
                    delete pNode;
                    pNode = NULL;
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }

                if ( !pNode->IsGroupNode() )
                {
                    delete pNode;
                    pNode = NULL;
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }
                pGroupNode = (CCxStructTreeNodeGroup *)pNode;
                m_vGroups.push_back( pGroupNode );
            }
        }

        for ( int i=0; i<(int)m_vGroups.size(); i++ )
        {
            m_mapGroupNode.insert( make_pair( m_vGroups[i]->m_strID, m_vGroups[i] ) );
        }

        if ( !obj["paramList"].isNull() && obj["paramList"].isArray() )
        {
            arrValue = obj["paramList"];

            if ( pTree != NULL )
            {
                pTree->m_bNodeParseing = TRUE;
                pTree->m_mapParseNodeCache.clear();
            }

            for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
            {
                str = ( (*itr)["nodeType"].isString() ) ? (*itr)["nodeType"].asCString() : _T("");
                int nNodeType = CCxStructTreeNode::ConvertNodeType( (LPCTSTR)str );
                pNode = CCxStructTreeNode::GetNewNodeByType( nNodeType, pTree );
                if ( pNode == NULL )
                {
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }

                if ( !pNode->Parse( *itr/*reinterpret_cast< LPVOID > ( (Json::Value *)& (*itr) )*/
                                    , pNode, nNodeType, NULL ) )
                {
                    delete pNode;
                    pNode = NULL;
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }

                if ( !pNode->IsParamNode() )
                {
                    delete pNode;
                    pNode = NULL;
                    Clear();
                    if ( pTree != NULL )
                    {
                        pTree->m_bNodeParseing = FALSE;
                        pTree->m_mapParseNodeCache.clear();
                    }
                    return FALSE;
                }
                pParamNode = (CCxStructTreeNodeParam *)pNode;
                m_vParams.push_back( pParamNode );
            }
        }

        for ( int i=0; i<(int)m_vParams.size(); i++ )
        {
            m_mapParamNode.insert( make_pair( m_vParams[i]->m_strID, m_vParams[i] ) );
        }

        if ( !obj["operateList"].isNull() && obj["operateList"].isArray() )
        {
            arrValue = obj["operateList"];

            for ( Json::Value::iterator itr = arrValue.begin(); itr != arrValue.end(); ++itr)
            {
                pOperatorData = new CCxStructTreeUpdateParamsOperatorData();
                pOperatorData->m_strId = ( (*itr)["id"].isString() ) ? (*itr)["id"].asCString() : _T("");
                pOperatorData->m_strFlag = ( (*itr)["flag"].isString() ) ? (*itr)["flag"].asCString() : _T("");
                m_vOperators.push_back( pOperatorData );
            }
        }

        if ( pTree != NULL )
        {
            pTree->m_bNodeParseing = FALSE;
            pTree->m_mapParseNodeCache.clear();
        }
    }
    catch (...)
    {
        Clear();
        if ( pTree != NULL )
        {
            pTree->m_bNodeParseing = FALSE;
            pTree->m_mapParseNodeCache.clear();
        }
        return FALSE;
    }

    return TRUE;
}
Example #22
0
bool cPlayer::LoadFromDisk()
{
	LoadPermissionsFromDisk();

	// Log player permissions, cause it's what the cool kids do
	LOGINFO("Player %s has permissions:", m_PlayerName.c_str() );
	for( PermissionMap::iterator itr = m_ResolvedPermissions.begin(); itr != m_ResolvedPermissions.end(); ++itr )
	{
		if( itr->second ) LOGINFO("%s", itr->first.c_str() );
	}

	AString SourceFile;
	Printf(SourceFile, "players/%s.json", m_PlayerName.c_str() );

	cFile f;
	if (!f.Open(SourceFile, cFile::fmRead))
	{
		// This is a new player whom we haven't seen yet, bail out, let them have the defaults
		return false;
	}

	AString buffer;
	if (f.ReadRestOfFile(buffer) != f.GetSize())
	{
		LOGWARNING("Cannot read player data from file \"%s\"", SourceFile.c_str()); 
		return false;
	}
	f.Close();

	Json::Value root;
	Json::Reader reader;
	if (!reader.parse(buffer, root, false))
	{
		LOGWARNING("Cannot parse player data in file \"%s\", player will be reset", SourceFile.c_str());
	}

	Json::Value & JSON_PlayerPosition = root["position"];
	if (JSON_PlayerPosition.size() == 3)
	{
		SetPosX(JSON_PlayerPosition[(unsigned int)0].asDouble());
		SetPosY(JSON_PlayerPosition[(unsigned int)1].asDouble());
		SetPosZ(JSON_PlayerPosition[(unsigned int)2].asDouble());
		m_LastPosX = GetPosX();
		m_LastPosY = GetPosY();
		m_LastPosZ = GetPosZ();
		m_LastFoodPos = GetPosition();
	}

	Json::Value & JSON_PlayerRotation = root["rotation"];
	if (JSON_PlayerRotation.size() == 3)
	{
		SetRotation ((float)JSON_PlayerRotation[(unsigned int)0].asDouble());
		SetPitch    ((float)JSON_PlayerRotation[(unsigned int)1].asDouble());
		SetRoll     ((float)JSON_PlayerRotation[(unsigned int)2].asDouble());
	}

	m_Health = root.get("health", 0).asInt();
	m_AirLevel            = root.get("air",            MAX_AIR_LEVEL).asInt();
	m_FoodLevel           = root.get("food",           MAX_FOOD_LEVEL).asInt();
	m_FoodSaturationLevel = root.get("foodSaturation", MAX_FOOD_LEVEL).asDouble();
	m_FoodTickTimer       = root.get("foodTickTimer",  0).asInt();
	m_FoodExhaustionLevel = root.get("foodExhaustion", 0).asDouble();

	m_GameMode = (eGameMode) root.get("gamemode", eGameMode_NotSet).asInt();
	
	m_Inventory.LoadFromJson(root["inventory"]);

	m_LoadedWorldName = root.get("world", "world").asString();
	
	LOGD("Player \"%s\" was read from file, spawning at {%.2f, %.2f, %.2f} in world \"%s\"",
		m_PlayerName.c_str(), GetPosX(), GetPosY(), GetPosZ(), m_LoadedWorldName.c_str()
	);
	
	return true;
}
Example #23
0
detect::detect(std::string url, std::string cfgfile) 
{
    try 
    {
        std::map<std::string, std::string> options = get_options(cfgfile);
        std::string json = http_get(options["SERVER"] + 
                                    options["VERSION"] + 
                                    std::string("/detection/detect?url=") + 
                                    url + 
                                    "&api_secret=" + 
                                    options["API_SECRET"] + 
                                    "&api_key=" + 
                                    options["API_KEY"]);
        Json::Reader reader;
        Json::Value root;
        Json::Value faces;
        unsigned int i;

        reader.parse(json, root, false);
        faces = root["face"];
        for (i = 0; i < faces.size(); i++) 
        {
            age_t age;
            age.range = faces[i]["attribute"]["age"]["range"].asUInt();
            age.value = faces[i]["attribute"]["age"]["value"].asUInt();
            
            gender_t gender;
            gender.confidence = faces[i]["attribute"]["gender"]["confidence"].asFloat();
            gender.value = faces[i]["attribute"]["gender"]["value"].asString();
            
            race_t race;
            race.confidence = faces[i]["attribute"]["race"]["confidence"].asFloat();
            race.value = faces[i]["attribute"]["race"]["value"].asString();
            
            attribute_t attribute;
            attribute.age = age;
            attribute.gender = gender;
            attribute.race = race;
            attribute.smiling = faces[i]["attribute"]["smiling"]["value"].asFloat();
            
            face_t face;
            face.attribute = attribute;
            face.face_id = faces[i]["face_id"].asString();
           
            position_t position;
            point_t center;
            center.x = faces[i]["position"]["center"]["x"].asFloat();
            center.y = faces[i]["position"]["center"]["y"].asFloat();
            position.center = center;
            point_t eye_left;
            eye_left.x = faces[i]["position"]["eye_left"]["x"].asFloat();
            eye_left.y = faces[i]["position"]["eye_left"]["y"].asFloat();
            position.eye_left = eye_left;
            point_t eye_right;
            eye_right.x = faces[i]["position"]["eye_right"]["x"].asFloat();
            eye_right.y = faces[i]["position"]["eye_right"]["y"].asFloat();
            position.eye_right = eye_right;
            position.height = faces[i]["position"]["height"].asFloat();
            point_t mouth_left;                                                   
            mouth_left.x = faces[i]["position"]["mouth_left"]["x"].asFloat();          
            mouth_left.y = faces[i]["position"]["mouth_left"]["y"].asFloat();          
            position.mouth_left = mouth_left;
            point_t mouth_right;                                                  
            mouth_right.x = faces[i]["position"]["mouth_right"]["x"].asFloat();        
            mouth_right.y = faces[i]["position"]["mouth_right"]["y"].asFloat();        
            position.mouth_right = mouth_right;
            point_t nose;                                                     
            nose.x = faces[i]["position"]["nose"]["x"].asFloat();           
            nose.y = faces[i]["position"]["nose"]["y"].asFloat();           
            position.nose = nose;
            position.width = faces[i]["position"]["width"].asFloat();
            face.position = position;

            m_faces.push_back(face);
        }
    } 
    catch (std::string ex) 
    {
        std::cout << ex << std::endl;
    }
}
Example #24
0
/* create_poll: create a strawpoll, return id */
static int create_poll(char *out, char *pollbuf, struct command *c)
{
	/* json values to hold created poll, poll options and http response */
	Json::Value poll, options(Json::arrayValue), response;
	Json::FastWriter fw;
	Json::Reader reader;
	cpr::Response resp;
	char buf[MAX_MSG];
	char *quest, *s, *t;

	argvcat(buf, c->argc, c->argv, l_optind, 1);
	quest = buf;
	if (!(s = strchr(quest, '|'))) {
		if (!binary) {
			snprintf(out, MAX_MSG, "%s: poll must have a question "
					"and at least two answers", c->argv[0]);
			return EXIT_FAILURE;
		}
	} else {
		*s = '\0';
		if (binary) {
			snprintf(out, MAX_MSG, "%s: cannot provide answers "
					"for binary poll", c->argv[0]);
			return EXIT_FAILURE;
		}
	}

	if (binary) {
		options.append("yes");
		options.append("no");
	} else {
		for (++s; *s && (t = strchr(s, '|')); s = t + 1) {
			*t = '\0';
			options.append(s);
		}
		if (*s)
			options.append(s);
	}

	if (options.size() < 2) {
		snprintf(out, MAX_MSG, "%s: poll must have a question "
				"and at least two answers", c->argv[0]);
		return EXIT_FAILURE;
	}

	/* populate the poll json */
	poll["title"] = quest;
	poll["options"] = options;
	poll["captcha"] = captcha;
	poll["multi"] = multi;

	/* format and post the poll */
	snprintf(buf, MAX_MSG, "%s%s", STRAWPOLL_HOST, STRAWPOLL_API);
	resp = cpr::Post(cpr::Url(buf), cpr::Body(fw.write(poll)), cpr::Header{
			{ "Connection", "close" },
			{ "Content-Type", "application/json" }
		});

	/* read id from response */
	if (reader.parse(resp.text, response)) {
		if (!response.isMember("id")) {
			snprintf(out, MAX_MSG, "%s: poll could not be created",
					c->argv[0]);
			return EXIT_FAILURE;
		}
		snprintf(pollbuf, MAX_LEN, "%d", response["id"].asInt());
		snprintf(out, MAX_MSG, "[STRAWPOLL] %s/%s",
				STRAWPOLL_HOST, pollbuf);
		return EXIT_SUCCESS;
	}
	snprintf(out, MAX_MSG, "%s: could not parse response", c->argv[0]);
	return EXIT_FAILURE;
}
int main(int argc,char** argv){
	int daemonize=0;
	int version=0;
	const char* group="www-data";

	try {
		openlog("ftd",LOG_PERROR,LOG_DAEMON);
		// Set logmask, default is LOG_NOTICE (5)
		setlogmask(LOG_UPTO( FtdConfig::Instance().GetIntegerOrDefault("general","loglevel",5)));

		signal(SIGPIPE, SIG_IGN);
		signal(SIGINT, sighandler);
		signal(SIGTERM,sighandler);

		poptContext optCon;
		struct poptOption opts[]={
			{"fg",'f',POPT_ARG_NONE,&daemonize,0,"Run in foreground, dont daemonize",NULL},
			{"version",'v',POPT_ARG_NONE,&version,0,"Show version",NULL},
			{"group",'g',POPT_ARG_STRING,&group,0,"Group allowed to talk to ftd","group"},
			POPT_AUTOHELP
			{ NULL, 0, 0, NULL, 0}
		};

		optCon=poptGetContext(NULL,argc,(const char**)argv,opts,0);
		int rc = poptGetNextOpt(optCon);

		if (rc<-1) {
			fprintf(stderr, "%s: %s\n",
					poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
					poptStrerror(rc));
			return 1;
		}

		poptFreeContext(optCon);

		if (version) {
			cerr << "Version: "<< appversion<<endl;
			cerr << "Built  : "<< builddate<<endl;
			return 0;
		}

		if (getuid()!=0) {
			syslog(LOG_ERR, "Started as non root terminating");
			cerr << "You must be root to run application"<<endl;
			return 1;
		}

		syslog(LOG_INFO,"Started");

		if (!daemonize) {
			daemon(1,0);
			syslog(LOG_INFO,"Daemonizing");
			ofstream pidfile("/var/run/ftd.pid");
			pidfile<<getpid()<<endl;
			pidfile.close();
		}

		unlink("/tmp/ftdaemon");

		UnixServerSocket sock(SOCK_STREAM,"/tmp/ftdaemon");
		chmod("/tmp/ftdaemon",0660);
		FileUtils::Chown("/tmp/ftdaemon","root",group);

		FtdApp& fapp=FtdApp::Instance();
		// Order is important here both curl and torrent downloader acccept the same scheme
		fapp.AddFilter(&SocketFdDownloadManager::Instance());
		fapp.AddFilter(&CurlDownloadManager::Instance());
		fapp.AddFilter(&TorrentDownloadManager::Instance());

		Json::Reader reader;
		do {
			try{
			
				UnixClientSocket* con=sock.Accept();
				
				if(!con){
					continue;
				}

				char buf[16384];
				ssize_t r=con->Receive(buf, 16384);
				if(r>0){
					buf[r]=0;
					Json::Value res;
					bool success=reader.parse(buf,res);
					if(!success){
						syslog(LOG_ERR,"No valid request");
						fapp.SendFail(con);
						delete con;
						continue;
					}
					if(!res.isMember("cmd")){
						syslog(LOG_ERR,"Request missing command");
						fapp.SendFail(con);
						delete con;
						continue;
					}
					if(!res["cmd"].isInt()){
						syslog(LOG_ERR,"Command illegal format");
						fapp.SendFail(con);
						delete con;
						continue;
					}
#ifdef DEBUG
					printValueTree(res);
#endif
					switch(res["cmd"].asInt()){
					case ADD_DOWNLOAD:
						fapp.AddDownload(res,con);
						break;
					case CANCEL_DOWNLOAD:
						fapp.CancelDownload(res);
						break;
					case LIST_DOWNLOADS:
						fapp.ListDownloads(res,con);
						break;
					case GET_DOWNLOAD_THROTTLE:
						fapp.GetDownloadThrottle(res,con);
						break;
					case SET_DOWNLOAD_THROTTLE:
						fapp.SetDownloadThrottle(res,con);
						break;
					case GET_UPLOAD_THROTTLE:
						fapp.GetUploadThrottle(res,con);
						break;
					case SET_UPLOAD_THROTTLE:
						fapp.SetUploadThrottle(res,con);
						break;
					case CMD_SHUTDOWN:
						do_shutdown=true;
						fapp.SendOk(con);
						break;
					default:
						fapp.SendFail(con);
						break;
					}
						
				}
				delete con;
			}catch(std::runtime_error* err){
				syslog(LOG_NOTICE,"Caught exception waiting for message: [%s]",err->what());
			}

		} while ( !do_shutdown);

	} catch (std::runtime_error* err) {
		cout << "Caught exception:"<<err->what()<<endl;
		return 1;
	}

	if(do_shutdown){
		syslog(LOG_NOTICE,"shutting down");
		FtdApp::Instance().ShutDown();
		TorrentDownloadManager::Instance().Shutdown();
		syslog(LOG_NOTICE,"terminating");
	}
    
	return 0;
}
Example #26
0
// General search
SearchResponse& sbol::PartShop::search(std::string search_text, rdf_type object_type, int offset, int limit)
{
    string url = parseURLDomain(resource);
    
    /* Perform HTTP request */
    string response;
    CURL *curl;
    CURLcode res;
    
    /* In windows, this will init the winsock stuff */
    curl_global_init(CURL_GLOBAL_ALL);
    
    struct curl_slist *headers = NULL;
    //    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
    //    headers = curl_slist_append(headers, "charsets: utf-8");
    
    /* get a curl handle */
    curl = curl_easy_init();
    if(curl) {
        /* Specify the GET data */
        // Specify the type of SBOL object to search for
        string parameters = "objectType=" + parseClassName(object_type) + "&";
        
        // Specify partial search text. Specify how many records to retrieve
        parameters = parameters + search_text;
        
        encode_http(search_text);
        
        // Specify how many records to retrieve
        parameters += "/?offset=" + to_string(offset) + "&limit=" + to_string(limit);
        
        parameters = url + "/remoteSearch/" + parameters;
        
        /* First set the URL that is about to receive our GET. */
        //curl_easy_setopt(curl, CURLOPT_URL, Config::getOption("validator_url").c_str());
        curl_easy_setopt(curl, CURLOPT_URL, parameters.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        
        /* Now specify the callback to read the response into string */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if(res != CURLE_OK)
            throw SBOLError(SBOL_ERROR_BAD_HTTP_REQUEST, "Attempt to validate online failed with " + string(curl_easy_strerror(res)));
        
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    curl_slist_free_all(headers);
    curl_global_cleanup();
    
    SearchResponse& search_response = * new SearchResponse();
    Json::Value json_response;
    Json::Reader reader;
    bool parsed = reader.parse( response, json_response );     //parse process
    if ( parsed )
    {
        for( Json::ValueIterator i_entry = json_response.begin() ; i_entry != json_response.end(); i_entry++ )
        {
            Json::Value json_entry = *i_entry;
            Identified* record = new Identified(SBOL_IDENTIFIED, "dummy", "0");
            record->identity.set( json_entry.get("uri", response ).asString() );
            record->displayId.set( json_entry.get("displayId", response ).asString() );
            record->name.set( json_entry.get("name", response ).asString() );
            record->description.set( json_entry.get("description", response ).asString() );
            record->version.set( json_entry.get("version", response ).asString() );
            search_response.records.push_back(record);
        }
    }
    else
        throw SBOLError(SBOL_ERROR_BAD_HTTP_REQUEST, "Search failed with error message" + response);
    return search_response;
};
Example #27
0
//TODO: Abstract create entity methods, take a list of images from a file + default values.
//      These files will have list of components and their default values.
//      E.g. [name:Tree],[SpriteComponent:filePath,redraw,isLoaded],etc. JSON would be handy for this.
void GameWorld::CreatePlayerEntity()
{
    //TODO: Entity must correspond with components place in component vector.
    //TODO: Let entitys be a pair, a bool determining existance and its id or index of the array for any component identified by the entity
    //      E.G. SpriteComponents[newEntity] = new Sprite;
    //      Need to work out how to do this. Probably have to revert to arrays and have a fixed pool of entitys.

    Json::Value root;
    Json::Value allEntities;
    Json::Value entity;
    Json::Value component;
    Json::Value spriteComponent;
    Json::Reader reader;
    Json::Value positionComponent;

    std::filebuf fb;
    if (fb.open ("C:/Devroot/Game_Engine/bin/Debug/world_entitys.txt",std::ios::in))
    {
        std::istream is(&fb);

        bool parsingSuccessful = reader.parse( is, root );
        if ( !parsingSuccessful )
        {
            // report to the user the failure and their locations in the document.
            std::cout << "Failed to parse configuration\n" << std::endl;
            std::cout << reader.getFormatedErrorMessages() << std::endl;
        }
    };
    fb.close();

    allEntities = root["entities"];

    for ( int i = 0; i < allEntities.size(); ++i )  // Iterates over the sequence elements.
    {
        int newEntity = m_EnityManager.CreateNewEntity();
        entity = allEntities[i];

        for(int j = 0; j < entity.size();++j)
        {
            component = entity[j];
            spriteComponent = component["Sprite"];
            positionComponent = component["Position"];

            if(spriteComponent != Json::nullValue)
            {
                shared_ptr<Sprite> newSprite = shared_ptr<Sprite>(new Sprite);
                newSprite->entity = newEntity;
                newSprite->texture = NULL;

                for(int x=0; x < spriteComponent.size();++x)
                {
                    Json::Value spriteComponentItr = spriteComponent[x];
                    Json::Value filePath = spriteComponentItr["FilePath"];
                    Json::Value reDraw = spriteComponentItr["reDraw"];
                    Json::Value isLoaded = spriteComponentItr["isLoaded"];
                    if(filePath != Json::nullValue)
                    {
                        newSprite->filePath = filePath.asString();
                    }
                    if(reDraw != Json::nullValue)
                    {
                        newSprite->redraw = reDraw.asBool();
                    }
                    if(isLoaded != Json::nullValue)
                    {
                        newSprite->isLoaded = isLoaded.asBool();
                    }
                }

                m_ComponentStore.AddSpriteComponent(newSprite);
            }
            if(positionComponent != Json::nullValue)
            {
                shared_ptr<Position> newPosition = shared_ptr<Position>(new Position);
                newPosition->entity = newEntity;

                for(int x=0; x < positionComponent.size(); ++x)
                {
                    Json::Value positionComponentItr = positionComponent[x];
                    Json::Value xPos = positionComponentItr["x"];
                    Json::Value yPos = positionComponentItr["y"];
                    if(xPos != Json::nullValue)
                    {
                        newPosition->x = xPos.asInt();
                    }
                    if(yPos != Json::nullValue)
                    {
                        newPosition->y = yPos.asInt();
                    }
                }
                m_ComponentStore.AddPositionComponent(newPosition);
            }
        }
    }
}
Example #28
0
// Advanced search
SearchResponse& sbol::PartShop::search(SearchQuery& q)
{
    string url = parseURLDomain(resource);
    
    /* Perform HTTP request */
    string response;
    CURL *curl;
    CURLcode res;
    
    /* In windows, this will init the winsock stuff */
    curl_global_init(CURL_GLOBAL_ALL);
    
    struct curl_slist *headers = NULL;
    //    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
    //    headers = curl_slist_append(headers, "charsets: utf-8");
    
    /* get a curl handle */
    curl = curl_easy_init();
    
    /* Specify the GET parameters */
    if(curl)
    {
        string parameters;
        // Specify the type of SBOL object to search for
        if (q["objectType"].size() == 1)
            parameters = "objectType=" + parseClassName(q["objectType"].get()) + "&";
        else
            throw SBOLError(SBOL_ERROR_INVALID_ARGUMENT, "SearchQuery is invalid because it does not have an objectType specified");
        
        // Get the search criteria, while ignoring special search parameters like objectType, offset, and limit
        vector<string> search_criteria = q.getProperties();
        auto i_ignore = std::find(std::begin(search_criteria), std::end(search_criteria), SBOL_IDENTITY);
        search_criteria.erase(i_ignore);
        i_ignore = std::find(std::begin(search_criteria), std::end(search_criteria), SBOL_URI "#objectType");
        search_criteria.erase(i_ignore);
        i_ignore = std::find(std::begin(search_criteria), std::end(search_criteria), SBOL_URI "#offset");
        search_criteria.erase(i_ignore);
        i_ignore = std::find(std::begin(search_criteria), std::end(search_criteria), SBOL_URI "#limit");
        search_criteria.erase(i_ignore);
        
        // Form GET request from the search criteria
        for (auto & property_uri : search_criteria)
            for (auto & property_val : q.getPropertyValues(property_uri))
            {
                if (property_val.length() > 0)
                {
                    parameters += "<" + property_uri + ">=";
                    if (property_val.find("http") == 0)
                        parameters += "<" + property_val + ">&"; // encode property value as a URI
                    else
                        parameters += "'" + property_val + "'&"; // encode property value as a literal
                }
            }
        
        // Specify index of the first record to retrieve
        if (q["offset"].size() == 1)
            parameters += "/?offset=" + q["offset"].get();
        else
            throw SBOLError(SBOL_ERROR_INVALID_ARGUMENT, "Invalid offset parameter specified");
        
        // Specify how many records to retrieve
        if (q["limit"].size() == 1)
            parameters += "&limit=" + q["limit"].get();
        else
            throw SBOLError(SBOL_ERROR_INVALID_ARGUMENT, "Invalid limit parameter specified");
        
        encode_http(parameters);
        parameters = url + "/remoteSearch/" + parameters;
        
        /* First set the URL that is about to receive our GET. */
        //curl_easy_setopt(curl, CURLOPT_URL, Config::getOption("validator_url").c_str());
        curl_easy_setopt(curl, CURLOPT_URL, parameters.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        
        /* Now specify the callback to read the response into string */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if(res != CURLE_OK)
            throw SBOLError(SBOL_ERROR_BAD_HTTP_REQUEST, "Attempt to validate online failed with " + string(curl_easy_strerror(res)));
        
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    curl_slist_free_all(headers);
    curl_global_cleanup();
    
    SearchResponse& search_response = * new SearchResponse();
    Json::Value json_response;
    Json::Reader reader;
    bool parsed = reader.parse( response, json_response );     //parse process
    if ( parsed )
    {
        for( Json::ValueIterator i_entry = json_response.begin() ; i_entry != json_response.end(); i_entry++ )
        {
            Json::Value json_entry = *i_entry;
            Identified* record = new Identified(SBOL_IDENTIFIED, "dummy", "0");
            record->identity.set( json_entry.get("uri", response ).asString() );
            record->displayId.set( json_entry.get("displayId", response ).asString() );
            record->name.set( json_entry.get("name", response ).asString() );
            record->description.set( json_entry.get("description", response ).asString() );
            record->version.set( json_entry.get("version", response ).asString() );
            search_response.records.push_back(record);
        }
    }
    else
        throw SBOLError(SBOL_ERROR_BAD_HTTP_REQUEST, "Search failed with error message" + response);
    return search_response;
};
Example #29
0
std::string 
Reader::getFormatedErrorMessages() const
{
   std::string formattedMessage;
   for ( Errors::const_iterator itError = errors_.begin();
         itError != errors_.end();
         ++itError )
   {
      const ErrorInfo &error = *itError;
      formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
      formattedMessage += "  " + error.message_ + "\n";
      if ( error.extra_ )
         formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
   }
   return formattedMessage;
}


std::istream& operator>>( std::istream &sin, Value &root )
{
    Json::Reader reader;
    bool ok = reader.parse(sin, root, true);
    //JSON_ASSERT( ok );
    if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
    return sin;
}


} // namespace Json
void json_writer_t::update(const game_t &game) {
    auto &packets = root["packets"];

    bounding_box_t bounding_box = game.get_arena().bounding_box;

    // copy boundary values
    Json::Value coordinate(Json::arrayValue);
    coordinate.append(std::get<0>(bounding_box.bottom_left));
    coordinate.append(std::get<1>(bounding_box.bottom_left));
    root["map_boundaries"].append(coordinate);
    coordinate.clear();
    coordinate.append(std::get<0>(bounding_box.upper_right));
    coordinate.append(std::get<1>(bounding_box.upper_right));
    root["map_boundaries"].append(coordinate);
    
    root["recorder_id"] = game.get_recorder_id();

    Json::Value summary;
    Json::Reader reader;
    
    const buffer_t &buffer = game.get_game_begin();
    std::string summary_str(buffer.begin(), buffer.end());
    reader.parse(summary_str, summary);

    root["summary"] = summary;

    for (auto &packet : game.get_packets()) {
        Json::Value value(Json::objectValue);

        if (packet.has_property(property_t::type)) {
            value["type"] = packet.type();
        }
        
        if (packet.has_property(property_t::clock)) {
            value["clock"] = packet.clock();
        }

        if (packet.has_property(property_t::player_id)) {
            value["player_id"] = packet.player_id();
            int team_id = game.get_team_id(packet.player_id());
            if (team_id != -1) {
                value["team"] = team_id;
            }
        }

        if (packet.has_property(property_t::position)) {
            Json::Value positionValue(Json::arrayValue);
            const auto &position = packet.position();
            positionValue.append(std::get<0>(position));
            positionValue.append(std::get<1>(position));
            positionValue.append(std::get<2>(position));
            value["position"] = positionValue;
        }

        if (packet.has_property(property_t::hull_orientation)) {
            Json::Value orientationValue(Json::arrayValue);
            const auto &orientation = packet.hull_orientation();
            orientationValue.append(std::get<0>(orientation));
            orientationValue.append(std::get<1>(orientation));
            orientationValue.append(std::get<2>(orientation));
            value["hull_orientation"] = orientationValue;
        }

        if (packet.has_property(property_t::tank_destroyed)) {
            uint32_t target, destroyed_by;
            std::tie(target, destroyed_by) = packet.tank_destroyed();
            value["target"] = target;
            value["destroyed_by"] = destroyed_by;
        }

        if (packet.has_property(property_t::health)) {
            value["health"] = packet.health();
        }

        if (packet.has_property(property_t::source)) {
            value["source"] = packet.source();
        }

        if (packet.has_property(property_t::message)) {
            value["message"] = packet.message();
        }

        if (packet.has_property(property_t::sub_type)) {
            value["sub_type"] = packet.sub_type();
        }

        if (packet.has_property(property_t::target)) {
            value["target"] = packet.target();
        }

        if (packet.has_property(property_t::destroyed_track_id)) {
            value["destroyed_track_id"] = packet.destroyed_track_id();
        }

        if (packet.has_property(property_t::alt_track_state)) {
            value["alt_track_state"] = packet.alt_track_state();
        }

        packets.append(value);
    }
}