Example #1
0
File: virt.cpp Project: kohn/rsi
// read /var/lib/libvirt/dnsmasq/default.leases to get ip
// domain must use DHCP
std::string VM_Controller::get_vm_ip_by_name(std::string domain_name){
    LOG_INFO(domain_name);
    Json::Value j;
    virDomainPtr dom = virDomainLookupByName(_conn, domain_name.c_str());
    if(dom == NULL){
        Json::Value j;
        j["status"] = "no such domain";
        return j.toStyledString();
    }
        
    std::string mac = _get_vm_mac(dom);
    LOG_INFO(mac);
    virDomainFree(dom);

    std::ifstream leases("/var/lib/libvirt/dnsmasq/default.leases");
    while(!leases.eof()){
        std::string line;
        std::getline(leases, line);
        DEBUG(line);
        if(line == "")
            break;
        std::vector<std::string> v;
        Tools::split(line, v, ' ');
        if(v[1] == mac){
            j["ip"] = v[2];
            j["status"] = "ok";
            return j.toStyledString();
        }
    }
    leases.close();
    j["status"] = "Could not find ip for the mac address";
    return j.toStyledString();
}
void EvaluatePrequential::doSetParams() {
	mDataSource = getParam("DataSource", "");

	Json::Value jv = getParam("Learner");
	if (! jv.isNull()) {
		mLearnerName = jv["Name"].asString();
		mLearnerParams = jv.toStyledString();
	}

	jv = getParam("Evaluator");
	if (! jv.isNull()) {
		mEvaluatorName = jv["Name"].asString();
		mEvaluatorParams = jv.toStyledString();
	}
	else {
		mEvaluatorName = "BasicClassificationEvaluator";
	}

	mReaderName = getParam("Reader", "");
	if (mReaderName == "") {
		jv = getParam("Reader");
		if (! jv.isNull()) {
			mReaderName = jv["Name"].asString();
			mReaderParams = jv.toStyledString();
		}
	}
}
Example #3
0
 Json::Value Connection::process_result(const Json::Value& value) {
   if(value.isObject()) {
     Json::Value id = value["id"];
     if(!id.isIntegral() or id.asInt() != 0) {
       std::stringstream error;
       error << value.toStyledString() << " is no id=0";
       throw ConnectionError(error.str());
     }
     Json::Value jsonrpc = value["jsonrpc"];
     if(!jsonrpc.isString()) {
       std::stringstream error;
       error << value.toStyledString() << " has no string member: jsonrpc";
       throw ConnectionError(error.str());
     }
     Json::Value result = value["result"];
     if(!result.isObject()) {
       std::stringstream error;
       error << value.toStyledString() << " has no object member: result";
       throw ConnectionError(error.str());
     }
     return result;
   } else {
     std::stringstream error;
     error << value.toStyledString() << " is no json object";
     throw ConnectionError(error.str());
   }
 }
Example #4
0
    Expectations::Expectations(Json::Value jsonElement) {
        if (jsonElement.empty()) {
            fIgnoreFailure = kDefaultIgnoreFailure;
        } else {
            Json::Value ignoreFailure = jsonElement[kJsonKey_ExpectedResults_IgnoreFailure];
            if (ignoreFailure.isNull()) {
                fIgnoreFailure = kDefaultIgnoreFailure;
            } else if (!ignoreFailure.isBool()) {
                SkDebugf("found non-boolean json value for key '%s' in element '%s'\n",
                         kJsonKey_ExpectedResults_IgnoreFailure,
                         jsonElement.toStyledString().c_str());
                DEBUGFAIL_SEE_STDERR;
                fIgnoreFailure = kDefaultIgnoreFailure;
            } else {
                fIgnoreFailure = ignoreFailure.asBool();
            }

            Json::Value allowedDigests = jsonElement[kJsonKey_ExpectedResults_AllowedDigests];
            if (allowedDigests.isNull()) {
                // ok, we'll just assume there aren't any AllowedDigests to compare against
            } else if (!allowedDigests.isArray()) {
                SkDebugf("found non-array json value for key '%s' in element '%s'\n",
                         kJsonKey_ExpectedResults_AllowedDigests,
                         jsonElement.toStyledString().c_str());
                DEBUGFAIL_SEE_STDERR;
            } else {
                for (Json::ArrayIndex i=0; i<allowedDigests.size(); i++) {
                    fAllowedResultDigests.push_back(GmResultDigest(allowedDigests[i]));
                }
            }
        }
    }
Example #5
0
bool save_login()
{
	Json::Value login;

	login["pwd"] = base64::base64_encode((UCHAR*)XorCrypt::Xor(login_pwd, XOR_PWD).c_str(), login_pwd.length());
	login["user"] = login_name;

	TCHAR szPath[MAX_PATH] = { 0 };
	SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szPath);
	::PathAppend(szPath, APP_NAME);

	if (!PathFileExists(szPath))
	{
		SHCreateDirectoryEx(NULL, szPath, NULL);
	}

	::PathAppend(szPath, LOGIN_DAT);

	HANDLE hFile = CreateFile(szPath, GENERIC_WRITE | GENERIC_READ,
		0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		return false;
	DWORD dwWritten = 0;
	::WriteFile(hFile, login.toStyledString().c_str(), login.toStyledString().size(), &dwWritten, NULL);
	::FlushFileBuffers(hFile);
	::CloseHandle(hFile);

	return true;
}
 GmResultDigest::GmResultDigest(const Json::Value &jsonTypeValuePair) {
     fIsValid = false;
     if (!jsonTypeValuePair.isArray()) {
         gm_fprintf(stderr, "found non-array json value when parsing GmResultDigest: %s\n",
                    jsonTypeValuePair.toStyledString().c_str());
         DEBUGFAIL_SEE_STDERR;
     } else if (2 != jsonTypeValuePair.size()) {
         gm_fprintf(stderr, "found json array with wrong size when parsing GmResultDigest: %s\n",
                    jsonTypeValuePair.toStyledString().c_str());
         DEBUGFAIL_SEE_STDERR;
     } else {
         // TODO(epoger): The current implementation assumes that the
         // result digest is always of type kJsonKey_Hashtype_Bitmap_64bitMD5
         Json::Value jsonHashValue = jsonTypeValuePair[1];
         if (!jsonHashValue.isIntegral()) {
             gm_fprintf(stderr,
                        "found non-integer jsonHashValue when parsing GmResultDigest: %s\n",
                        jsonTypeValuePair.toStyledString().c_str());
             DEBUGFAIL_SEE_STDERR;
         } else {
             fHashDigest = jsonHashValue.asUInt64();
             fIsValid = true;
         }
     }
 }
Example #7
0
void LCBattleScene::sendPosition(CCPoint pos){
    
    OBJ_GPoint point;
    point.x = pos.x;
    point.y = pos.y;
    
    
    Json::Value root;
    Json::Value jsPos;
    
    jsPos["x"] = pos.x;
    jsPos["y"] = pos.y;
    
    root["success"] = true;
    root["msg"] = "hello";
    root["type"] = OBJ_TYPE_GPOINT;

    root["jsondata"] = jsPos.toStyledString().c_str();

    
    std::string str = root.toStyledString();
    str = str + "\r\n";
    
    //CCLOG("%s %s %s", root.toStyledString().c_str(), jsPos.toStyledString().c_str(), str.c_str());
    
    OD_BYTEPTR buffer = (OD_BYTEPTR)malloc(1024);
    memcpy(buffer, str.c_str() , 1024);
    con->Send(buffer);
}
Example #8
0
File: virt.cpp Project: kohn/rsi
std::string VM_Controller::get_job_progress(int job_id){
    RSIClients * clients = RSIClients::get_instance();
    int progress = clients->download_progress(job_id);
    Json::Value j;

    if(progress < 0){
        j["status"] = "no such job";
        return j.toStyledString();
    }
    
    j["status"] = "ok";
    j["progress"] = progress;
    return j.toStyledString();
}
Example #9
0
bool PlayingCards::JsonDeserialization(const std::string &sJsonPlayingCards, std::string &sErrorMessage)
{
    Json::Reader jReader;
    Json::Value  jCards;
    Json::Value  jCard;
    Card cCard;

    if (jReader.parse(sJsonPlayingCards, jCards, false))
    {
        m_vCards.clear();

        for (Json::ValueIterator it = jCards.begin(); it != jCards.end(); ++it)
        {
            jCard = (*it);
            if (cCard.JsonDeserialization(jCard.toStyledString(), sErrorMessage))
            {
                m_vCards.push_back(cCard);
            }
            else
            {
                return false;
            }
        }

        return true;
    }
    else
    {
        sErrorMessage = jReader.getFormattedErrorMessages();
        return false;
    }
}
Example #10
0
void Epoll::actionWhisper(Client* me, Json::Value &obj) {
	if (
		!obj["data"].isMember("uid") ||
		!obj["data"].isMember("content")
		) {
		return;
	}
	int uid = obj["data"]["uid"].asInt();
	Client *you = getClientByUID(uid);
	if(!you) {
		std::cout << "user uid:" << uid << " not exists!" << std::endl;
		return;
	}
	
	Json::Value target;
	target["uid"] = you->getUID();
	target["name"] = "你";
	
	Json::Value user;
	user["uid"]  = me->getUID();
	user["name"] = me->getName();
	
	Json::Value data;
	data["user"] = user;
	data["content"] = obj["data"]["content"].asString();
	data["target"] = target;
	
	Json::Value oops;
	oops["code"] = Message::sWhisper;
	oops["data"] = data;
	std::cout << user["name"].asString() << "对" << you->getName() << "说:" << data["content"].asString() << std::endl;
	you->send(oops.toStyledString());
}
Example #11
0
void Protocol::encode(std::string &value) const
{
    Json::Value root;
    JsonStream stream(root);
    encode(stream);
    std::string plain = root.toStyledString();
    CCLOG("==== Client send:%s ====", plain.c_str());
    if (needcrypt)
    {
        
        
        size_t length = plain.length();
        char *temp = new char[length + sizeof(type)];
        memcpy(temp, &type, sizeof(type));
        rc4_state state;
        rc4_init(&state, (const u_char *)OUTKEY.c_str(), OUTKEY.size());
        rc4_crypt(&state, (const u_char *)plain.c_str(), (u_char *)(temp + sizeof(type)), length);
        value.assign(temp, length + sizeof(type));
        delete[] temp;
    }
    else
    {
        char *temp = new char[sizeof(type) + plain.length()];
        memcpy(temp, &type, sizeof(type));
        memcpy(temp + sizeof(type), plain.c_str(), plain.length());
        value.assign(temp, plain.length() + sizeof(type));
    }
}
Example #12
0
void Epoll::takeoutClient(Client* client) {
	Json::Value oops;
	oops["code"] = Message::sTakeOut;
	client->send(oops.toStyledString());
	_clients.erase(_clients.find(client->getFileDescripto()));
	delete client;
}
UINT WINAPI SendDataThreadProc(LPVOID pParam) //发送数据的线程回调函数
{

	//创建CPU占用率性能计数器
	CPerformanceCounter CPUUseAge(TEXT("\\Processor(0)\\% Processor Time"));
	//创建内存占用率性能计数器
	CPerformanceCounter MemoryUseAge(TEXT("\\Memory\\Available MBytes"));
	//创建磁盘IO性能计数器
	CPerformanceCounter DiskUseAge(TEXT("\\PhysicalDisk(_Total)\\% Idle Time"));

	while(true)
	{
		Sleep(100);

		//得到当前计数器百分值
		double nCPUUseAge = CPUUseAge.GetCurrentValue();
		double nMemoryUseAge = 100 * (1 - MemoryUseAge.GetCurrentValue()/1976);
		double nDiskUseAge = 100 - floor(DiskUseAge.GetCurrentValue());

		//封装成JSON字符串
		Json::Value json;
		json["msg_type"] = Json::Value("data");
		json["cpu_use"] = Json::Value(nCPUUseAge);
		json["memory_use"] = Json::Value(nMemoryUseAge);
		json["disk_use"] = Json::Value(nDiskUseAge);
		string strText = json.toStyledString();

		//发送性能信息
		::send(sClient, strText.c_str(), strlen(strText.c_str()), 0);
	}
	return 1;
}
Example #14
0
void
CommandHandler::testAcc(std::string const& params, std::string& retStr)
{
    std::map<std::string, std::string> retMap;
    http::server::server::parseParams(params, retMap);
    Json::Value root;
    auto accName = retMap.find("name");
    if (accName == retMap.end())
    {
        root["status"] = "error";
        root["detail"] = "Bad HTTP GET: try something like: testacc?name=bob";
    }
    else
    {
        SecretKey key;
        if (accName->second == "root")
        {
            key = getRoot(mApp.getNetworkID());
        }
        else
        {
            key = getAccount(accName->second.c_str());
        }
        auto acc = loadAccount(key, mApp, false);
        if (acc)
        {
            root["name"] = accName->second;
            root["id"] = PubKeyUtils::toStrKey(acc->getID());
            root["balance"] = (Json::Int64)acc->getBalance();
            root["seqnum"] = (Json::UInt64)acc->getSeqNum();
        }
    }
    retStr = root.toStyledString();
}
Example #15
0
// Get all properties for a specific frame
string Deinterlace::PropertiesJSON(int requested_frame) {

	// Requested Point
	Point requested_point(requested_frame, requested_frame);

	// Generate JSON properties list
	Json::Value root;
	root["id"] = add_property_json("ID", 0.0, "string", Id(), false, 0, -1, -1, CONSTANT, -1, true);
	root["position"] = add_property_json("Position", Position(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["layer"] = add_property_json("Layer", Layer(), "int", "", false, 0, 0, 1000, CONSTANT, -1, false);
	root["start"] = add_property_json("Start", Start(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["end"] = add_property_json("End", End(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["duration"] = add_property_json("Duration", Duration(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, true);
	root["isOdd"] = add_property_json("Is Odd Frame", isOdd, "bool", "", false, 0, 0, 1, CONSTANT, -1, true);

	// Keep track of settings string
	stringstream properties;
	properties << 0.0f << Position() << Layer() << Start() << End() << Duration() << isOdd;

	// Add Hash of All property values
	root["hash"] = add_property_json("hash", 0.0, "string", properties.str(), false, 0, 0, 1, CONSTANT, -1, true);

	// Return formatted string
	return root.toStyledString();
}
Example #16
0
std::string SignupHandler::Handle(std::string const& postStr){
	Json::Value val;
	Json::Reader reader;
	
	if (reader.parse(postStr, val)){
                if(!val.isMember("user")
                    ||!val.isMember("pass")){
			throw IncorrectDataFormatException();
		}
		
		std::string username = val["user"].asString();
		std::string psw = val["pass"].asString();
		
		std::string status = "used_username";
		if (_DB->add_user(username, psw)){
				status = "success";
		}
		Json::Value result;
		result["status"] = status;
		return result.toStyledString();
	}
	else{
		throw IncorrectDataFormatException();
	}
}
Example #17
0
std::string Zerobuf::toJSON() const
{
    Json::Value rootJSON;
    for( const auto& valueSchema : getSchema().fields )
        addValueToJSON( rootJSON, valueSchema )
    return rootJSON.toStyledString();
}
Example #18
0
File: virt.cpp Project: kohn/rsi
std::string VM_Controller::port_forward(std::string host_ip_address,
                                        std::string ip_address,
                                        std::string port){
    std::vector<std::string> v;
    Tools::split(ip_address, v, '.');
    std::string host_port = v[3] + port;
    host_port = "15000";
    
    std::string cmd = "iptables -t nat -A PREROUTING -p tcp -d ";
    cmd += host_ip_address;
    cmd +=" --dport ";
    cmd += host_port;
    cmd += " -j DNAT --to ";
    cmd += ip_address + ":" + port;
    DEBUG(cmd);
    system(cmd.c_str());
    cmd = "iptables -I FORWARD -p tcp -d ";
    cmd += ip_address + "  --dport " + port + " -j ACCEPT";
    DEBUG(cmd);
    system(cmd.c_str());

    Json::Value j;
    j["status"] = "ok";
    j["host_port"] = host_port;
    return j.toStyledString();
}
Example #19
0
void TsHttpRpc::_rpc_func_set_config(const Json::Value& json_param, ex_astr& buf)
{
	// https://github.com/tp4a/teleport/wiki/TELEPORT-CORE-JSON-RPC#set_config
	/*
	{
	  "noop-timeout": 15     # 按分钟计
	}
	*/

	if (json_param.isArray()) {
		_create_json_ret(buf, TPE_PARAM);
		return;
	}

	if (json_param["noop_timeout"].isNull() || !json_param["noop_timeout"].isUInt()) {
		_create_json_ret(buf, TPE_PARAM);
		return;
	}

	int noop_timeout = json_param["noop_timeout"].asUInt();
	EXLOGV("[core] set run-time config:\n");
	EXLOGV("[core]   noop_timeout = %dm\n", noop_timeout);

	ex_astr sp = json_param.toStyledString();
	g_tpp_mgr.set_runtime_config(sp);

	_create_json_ret(buf, TPE_OK);
}
int UnitTestJsonCpp::Run(void)
{
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;

	for (int i = 0; i < 10; i ++)
	{
		item["key"] = i;
		arrayObj.append(item);
	}

	root["key1"] = "value1";
	root["key2"] = "value2";
	root["array"] = arrayObj;
	std::string out = root.toStyledString();
	std::cout << out << std::endl;


	Json::StyledWriter writer;   
	std::string output = writer.write(root);

	std::ofstream out_file("duplicate_config.json" );   
	out_file << output;
	out_file.flush();

	return 0;
}
/**
 * Obtiene los contactos que se encuentran registrados en el sistemas y estan conectados,
 * a partir de numeros de telefono que recibe
 *
 */
void Servicio::obtenerContactos() {
	Json::Value contactosTelefonoValue = this->getParametroArray(
	keyContantosTelefono, keyDefault);
	vector<string> contactosTelefono = StringUtil::jsonValueToVector(
			contactosTelefonoValue);

	Json::Value respuesta;
	int counter = 0;
	for (unsigned i = 0; i < contactosTelefono.size(); i++) {
		string telefonoActual = contactosTelefono[i];
		Usuario* usuario = Usuario::obtenerPorTelefono(telefonoActual);

		//Agrego los usuarios que estan registrados y que se encuentran conectados

		if (usuario->getId() != keyIdUsuarioNoEncontrado
				&& usuario->getEstadoConexion()) {
			respuesta["contactos"][counter][keyNombre] = usuario->getNombre();
			respuesta["contactos"][counter][keyTelefono] =
					usuario->getTelefono();
			respuesta["contactos"][counter][keyFotoDePerfil] =
					usuario->getFotoDePerfil();
			respuesta["contactos"][counter][keyLocalizacion] = usuario->getLocalizacion();
			counter++;
		}
	}

	this->responder(respuesta.toStyledString(), true);
}
Example #22
0
// --------------------- json rpc interface -----------------------
void RestServ::httpRpcRequest(mg_connection& nc, HttpMessage data)
{
    reset(data);

    StreamBuf buf{nc.send_mbuf};
    out_.rdbuf(&buf);
    out_.reset(200, "OK");
    try {
        if (uri_.empty() || uri_.top() != "rpc") {
            throw ForbiddenException{"URI not support"};
        }

        //process here
        data.data_to_arg();
        tinychain::commands cmd{data.vargv(), node_};
        Json::Value ret;
        cmd.exec(ret);

        out_<<ret.toStyledString();

    } catch (const std::exception& e) {
        out_ << e.what();
    } 

    out_.setContentLength(); 
}
Example #23
0
static int tolua_luaexport_JsonEncode00(lua_State* tolua_S)
{
	tolua_Error tolua_err;
	if (
		!tolua_istable(tolua_S,1,0,&tolua_err) ||
		!tolua_isnoobj(tolua_S,2,&tolua_err)
		)
	{
		tolua_error(tolua_S,"#ferror in function 'JsonEncode'.",&tolua_err);
		return 0;
	}
	else
	{
		Json::Value root;
		if (!table2json(tolua_S, root))
		{
			return 0;
		}

		string& str = root.toStyledString();

		tolua_pushstring(tolua_S,(const char*)str.c_str());
	}
	return 1;
}
Example #24
0
STDMETHODIMP CFileProCom::OpenFile(BSTR strInJson, BSTR* strOutJson)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	// TODO: 在此添加实现代码
	string strIn  = (strInJson!=NULL)? _bstr_t(strInJson):"";
	CString strInFile = "";

	Json::Reader reader;
	Json::Value obj( Json::objectValue );
	CString str;
	try
	{
		if (!reader.parse(strIn, obj, true)) return S_FALSE;
		if ( obj.isNull() || !obj.isObject() ) return S_FALSE;

		strInFile = ( obj["file"].isString()) ? obj["file"].asCString() : _T("");
	}
	catch (...)
	{
		return S_FALSE;
	}

	CFilePro filePro;
	bool bOk = filePro.OpenFile(strInFile);

	Json::Value objOut;
	objOut["flag"]=  Json::Value(bOk ? "true":"false");
	objOut["msg"] =  Json::Value(LPCTSTR(filePro.GetErrMsg()));

	CString strOut = objOut.toStyledString().c_str();
	*strOutJson = _bstr_t(strOut).GetBSTR();
	return S_OK;
}
jsontype_t          SpecificationParser::toJsonType             (Json::Value &val)
{
    jsontype_t result;
    switch(val.type())
    {
        case Json::uintValue:
        case Json::intValue:
            result =  JSON_INTEGER;
            break;
        case Json::realValue:
            result = JSON_REAL;
            break;
        case Json::stringValue:
            result = JSON_STRING;
            break;
        case Json::booleanValue:
            result = JSON_BOOLEAN;
            break;
        case Json::arrayValue:
            result = JSON_ARRAY;
            break;
        case Json::objectValue:
            result = JSON_OBJECT;
            break;
        default:
            throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX,"Unknown parameter type: "
                                   + val.toStyledString());
    }
    return result;
}
Example #26
0
STDMETHODIMP CFileProCom::GetAllNewItemTypes(BSTR strInJson, BSTR* strOutJson)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	// TODO: 在此添加实现代码
	CFilePro pro;
	vector<NewType> vItems;
	pro.GetAllDesktopRightMenuNewItems(vItems);

	Json::Value objOut;
	objOut["flag"]=  Json::Value(vItems.size()>0 ? "true":"false");
	objOut["msg"] =  Json::Value(vItems.size()>0 ? "":"获取新建文件类型错误!");

	Json::Value jsonTypeItems(Json::arrayValue);
	for (size_t i=0;i<vItems.size();i++)
	{
		Json::Value jnt;
		jnt["ext"] = Json::Value(vItems[i].m_strExt.c_str());
		jnt["disp"] = Json::Value(vItems[i].m_strDesrciption.c_str());
		jsonTypeItems.append(jnt);
	}

	objOut["types"] = jsonTypeItems;

	CString strOut = objOut.toStyledString().c_str();
	*strOutJson  = _bstr_t(strOut).GetBSTR();
	Fire_ReportCopyProgress(*strOutJson);
	return S_OK;
}
Example #27
0
void TsHttpRpc::_rpc_func_kill_sessions(const Json::Value& json_param, ex_astr& buf) {
	/*
	{
	"sessions": ["0123456", "ABCDEF", ...]
	}
	*/

	if (json_param.isArray()) {
		_create_json_ret(buf, TPE_PARAM);
		return;
	}

	if (json_param["sessions"].isNull() || !json_param["sessions"].isArray()) {
		_create_json_ret(buf, TPE_PARAM);
		return;
	}

	Json::Value s = json_param["sessions"];
	int cnt = s.size();
	for (int i = 0; i < cnt; ++i) {
		if (!s[i].isString()) {
			_create_json_ret(buf, TPE_PARAM);
			return;
		}
	}

	EXLOGV("[core] try to kill %d sessions.\n", cnt);
	ex_astr sp = s.toStyledString();
	g_tpp_mgr.kill_sessions(sp);

	_create_json_ret(buf, TPE_OK);
}
Example #28
0
// Get all properties for a specific frame
string ChromaKey::PropertiesJSON(int requested_frame) {

	// Requested Point
	Point requested_point(requested_frame, requested_frame);

	// Generate JSON properties list
	Json::Value root;
	root["id"] = add_property_json("ID", 0.0, "string", Id(), false, 0, -1, -1, CONSTANT, -1, true);
	root["position"] = add_property_json("Position", Position(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["layer"] = add_property_json("Layer", Layer(), "int", "", false, 0, 0, 1000, CONSTANT, -1, false);
	root["start"] = add_property_json("Start", Start(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["end"] = add_property_json("End", End(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, false);
	root["duration"] = add_property_json("Duration", Duration(), "float", "", false, 0, 0, 1000 * 60 * 30, CONSTANT, -1, true);

	// Keyframes
	root["color"]["red"] = add_property_json("Red", color.red.GetValue(requested_frame), "float", "", color.red.Contains(requested_point), color.red.GetCount(), -10000, 10000, color.red.GetClosestPoint(requested_point).interpolation, color.red.GetClosestPoint(requested_point).co.X, false);
	root["color"]["blue"] = add_property_json("Blue", color.blue.GetValue(requested_frame), "float", "", color.blue.Contains(requested_point), color.blue.GetCount(), -10000, 10000, color.blue.GetClosestPoint(requested_point).interpolation, color.blue.GetClosestPoint(requested_point).co.X, false);
	root["color"]["green"] = add_property_json("Green", color.green.GetValue(requested_frame), "float", "", color.green.Contains(requested_point), color.green.GetCount(), -10000, 10000, color.green.GetClosestPoint(requested_point).interpolation, color.green.GetClosestPoint(requested_point).co.X, false);
	root["fuzz"] = add_property_json("Fuzz", fuzz.GetValue(requested_frame), "float", "", fuzz.Contains(requested_point), fuzz.GetCount(), -10000, 10000, fuzz.GetClosestPoint(requested_point).interpolation, fuzz.GetClosestPoint(requested_point).co.X, false);

	// Keep track of settings string
	stringstream properties;
	properties << 0.0f << Position() << Layer() << Start() << End() << Duration() <<
			color.red.GetValue(requested_frame) << color.green.GetValue(requested_frame) <<
			color.blue.GetValue(requested_frame) << fuzz.GetValue(requested_frame);

	// Add Hash of All property values
	root["hash"] = add_property_json("hash", 0.0, "string", properties.str(), false, 0, 0, 1, CONSTANT, -1, true);

	// Return formatted string
	return root.toStyledString();
}
Example #29
0
Bounds::Bounds(const Json::Value& json) : m_min(), m_max(), m_mid()
{
    if (!json.isArray() || (json.size() != 4 && json.size() != 6))
    {
        throw std::runtime_error(
            "Invalid JSON Bounds specification: " + json.toStyledString());
    }

    const bool is3d(json.size() == 6);

    if (is3d)
    {
        m_min = Point(
                json.get(Json::ArrayIndex(0), 0).asDouble(),
                json.get(Json::ArrayIndex(1), 0).asDouble(),
                json.get(Json::ArrayIndex(2), 0).asDouble());
        m_max = Point(
                json.get(Json::ArrayIndex(3), 0).asDouble(),
                json.get(Json::ArrayIndex(4), 0).asDouble(),
                json.get(Json::ArrayIndex(5), 0).asDouble());
    }
    else
    {
        m_min = Point(
                json.get(Json::ArrayIndex(0), 0).asDouble(),
                json.get(Json::ArrayIndex(1), 0).asDouble());
        m_max = Point(
                json.get(Json::ArrayIndex(2), 0).asDouble(),
                json.get(Json::ArrayIndex(3), 0).asDouble());
    }

    Bounds self(m_min, m_max);
    *this = self;
}
Example #30
0
void JsonTree::write( DataTargetRef target, bool createDocument )
{
	// Declare output string
	string jsonString = "";

	try {
		
		// Create JsonCpp data to send to parser
		Json::Value value = createNativeDoc( createDocument );

		// This routine serializes JsonCpp data and formats it
		Json::StyledWriter writer;
		jsonString = writer.write( value.toStyledString() );
		boost::replace_all( jsonString, "\\n", "\r\n" );
		boost::replace_all( jsonString, "\\\"", "\"" );
		if( jsonString.length() >= 3 ) {
			jsonString = jsonString.substr( 1, boost::trim_copy( jsonString ).length() - 2 );
		}
		jsonString += "\0";
	}
	catch ( ... ) {
		throw ExcJsonParserError( "Unable to serialize JsonTree." );
	}

	// Save data to file
	OStreamRef os = target->getStream();
	os->writeData( jsonString.c_str(), jsonString.length() );
}