void NowPlayingNDK::NowPlayingSetMetadata(const std::string& callbackId, const std::string& data){
              // Parse the arg string as JSON
              Json::FastWriter writer;
              Json::Reader reader;
              Json::Value root;
              bool parse = reader.parse(data, root);

              if (!parse) {
                  Json::Value error;
                  error["result"] = "Cannot parse JSON object";
                  sendEvent(callbackId + " " + writer.write(error));
              } else {
                  QVariantMap metadata;

                  metadata[MetaData::Title] = QString::fromStdString(root["Title"].asString());
                  metadata[MetaData::Artist] = QString::fromStdString(root["Artist"].asString());
                  metadata[MetaData::Album] = QString::fromStdString(root["Album"].asString());


                  root["result"] = "SetMetadata Succeed.";
                  sendEvent(callbackId + " " + writer.write(root));
              }

      }
Ejemplo n.º 2
0
void HelloWorld::writeJsonCpp()
{
	Json::Value root;
	Json::FastWriter writer;
	Json::Value person;

	person["name"] = "hello world";
	person["age"] = 100;
	root.append(person);

	std::string json_file = writer.write(root);


	char filePath[1024]= {'\0'};
	memset(filePath,0,sizeof(filePath));
	strcat(filePath,CCFileUtils::sharedFileUtils()->getWriteablePath().c_str());
	strcat(filePath,"writeJsonCpp.json");

	FILE* file = fopen(filePath,"w+");

	fwrite(json_file.c_str(),json_file.size(),1,file);

	fclose(file);
}
Ejemplo n.º 3
0
bool CustomMsgForm::OnClicked(ui::EventArgs* param)
{
	std::wstring name = param->pSender->GetName();
	if (name == L"btn_send")
	{
		std::string attach_text = nbase::UTF16ToUTF8(GetRichText(richedit_attach_));
		if (attach_text.empty())
		{
			return true;
		}
		richedit_attach_->SetText(L"");
		Json::Value json;
		Json::FastWriter writer;
		json["id"] = "2";
		json["content"] = attach_text;

		nim::SysMessageSetting setting;
		setting.need_offline_ = msg_mode_->IsSelected() ? nim::BS_FALSE : nim::BS_TRUE;

		auto str = nim::SystemMsg::CreateCustomNotificationMsg(session_id_, session_type_ == nim::kNIMSessionTypeTeam ? nim::kNIMSysMsgTypeCustomTeamMsg : nim::kNIMSysMsgTypeCustomP2PMsg, QString::GetGUID(), writer.write(json), setting);
		nim::SystemMsg::SendCustomNotificationMsg(str);
	}
	return true;
}
void ApplyUserAttributes(std::string name, AtNode* node,std::vector<std::string> tags,ProcArgs & args)
{

   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.userAttributes.begin(); it!=args.userAttributes.end(); ++it)
   {
      Json::Value userAttributes;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          userAttributes = args.userAttributesRoot[*it];
        }
      }

      if(userAttributes.size() > 0)
      {
        for( Json::ValueIterator itr = userAttributes.begin() ; itr != userAttributes.end() ; itr++ ) 
        {
            std::string attribute = itr.key().asString();

            if( AiNodeLookUpUserParameter(node,attribute.c_str()))
              continue;

            const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
            Json::Value val = args.userAttributesRoot[*it][attribute];
            if( val.isString() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            } 
            else if( val.isBool() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_BOOLEAN);
              AiNodeSetBool(node, attribute.c_str(), val.asBool());
            }
            else if( val.isInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_INT);
              AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_UINT);
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            }
            else if(val.isDouble())
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_FLOAT);
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
            }
            else if(val.isArray()) 
            {              

              // in the future we will convert to an arnold array type for now lets just 
              // write out a json string

              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              Json::FastWriter writer;
              AiNodeSetStr(node, attribute.c_str(), writer.write(val).c_str());
              
              // AddUserGeomParams(node,attribute.c_str(),AI_TYPE_ARRAY );

              // // get the type of the first entry, this will be our key as to
              // // what type of data is in this array
              // Json::Value firstValue = val[0];
              // if (firstValue.isString())
              // {
              //   AtArray* arrayValues = AiArrayAllocate( val.size() , 1, AI_TYPE_STRING);

              //   for( uint idx = 0 ; idx != val.size() ; idx++ ) 
              //   {
              //     AiMsgInfo("[ABC] adding string %s to user array attribute '%s'",val[idx].asCString(),attribute.c_str());
              //     AiArraySetStr(arrayValues,idx,val[idx].asCString());
              //   }

              //   AiNodeSetArray(node, attribute.c_str(), arrayValues);         
              // }
     
            }

            // TODO color, matrix, vector

         }
      }
   }
}
Ejemplo n.º 5
0
const std::string ScrollableMessageMarshaller::toString(const ScrollableMessage& e)
{
  Json::FastWriter writer;
  return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
Ejemplo n.º 6
0
const std::string HMILevelMarshaller::toString(const HMILevel& e)
{
  Json::FastWriter writer;
  return e.mInternal==HMILevel::INVALID_ENUM ? "" : writer.write(toJSON(e));

}
Ejemplo n.º 7
0
void Sniffer::process_packet(u_char *user, const struct pcap_pkthdr *header, const u_char *bytes){
    struct ethhdr *ethh = (struct ethhdr*) bytes;

    char buffer[17];
    sprintf(buffer,"%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", ethh->h_dest[0], ethh->h_dest[1], ethh->h_dest[2], ethh->h_dest[3], ethh->h_dest[4], ethh->h_dest[5]);
    if(std::string(buffer, 17) != "01:80:C2:00:00:00")
        return;

    //handle payload
    const u_char *payload = bytes+sizeof(struct ethhdr);
    int psize = header->len - sizeof(struct ethhdr);
    //payload starts at logical link control level
    //llc has 3 bytes
    payload+=3;
    psize-=3;
    //payload is now at the start of the stp payload
    //protocol identifier stp (2 bytes)
    payload+=2;
    psize-=2;

    //one byte for version and bpdu type
    payload+=2;
    psize-=2;

    //tc flag
    bool tc = *(payload++);
    psize--;

    //root identifier
    //bridge priority is the next 2 bytes
    //actual bridge priority is 4 bits, 
    //then comes id extension with 12 bits
    
    //generate filters
    unsigned short extFilter = -1;
    extFilter = extFilter>>4;
    unsigned short prioFilter = extFilter<<12;
    
    unsigned short rPriority, rExtension;
    rPriority = htons(*((short*)payload));
    rExtension = rPriority & extFilter;
    rPriority = rPriority & prioFilter;
    payload+=2;
    psize-=2;
    //next 6 bytes is the root bridge id
    Mac rootMac(payload);
    payload+=6;
    psize-=6;

    //root path cost (4 bytes)
    payload+=4;
    psize-=4;

    //bridge identifier
    //bridge priority is the next 2 bytes
    unsigned short bPriority, bExtension;
    bPriority = htons(*((short*)payload));
    bExtension = bPriority & extFilter;
    bPriority = bPriority & prioFilter;
    payload+=2;
    psize-=2;
    //next 6 bytes is the bridge mac address
    Mac bridgeMac(payload);
    payload+=6;
    psize-=6;

    //next 2 bytes are port identifier
    payload+=2;
    psize-=2;

    //next 2 bytes is message age
    unsigned short messageAge;
    messageAge = *((short*)payload);
    payload+=2;
    psize-=2;

    //generate Bridge objects
    Bridge root(rootMac, rPriority, rExtension, 0);
    Bridge firstHop(bridgeMac, bPriority, bExtension, messageAge);

    //check if the two nodes are contained
    int rootContained = 0, oldHopMa = -1;
    for(Bridge b : bridges){
        if(b == root)
            rootContained = 1;
        if(b == firstHop)
            oldHopMa = b.getMessageAge();
    }

    //handle network changes
    if(rootContained){
        if(oldHopMa >= 0){
            //both contained
            if(oldHopMa != firstHop.getMessageAge()){
                //changes occured
                clearAndAdd(firstHop, root);
            }else{
                //everything is as it was
                //if something changed upstream a tc flag will be sent
                //->reset
                if(tc && !hadTC)
                    clearAndAdd(firstHop, root);
            }
        }else{
            //first hop not contained
            //this means that the node was plugged in on a different bridge
            //(most likely)
            //we don't know how long we were disconnected, so reregister the client
            if(!noConnect)
                client->regServer();
            clearAndAdd(firstHop, root);
        }
    }else{
        //root not contained
        if(oldHopMa >= 0){
            //if the first hop was contained this means there were some changes upstream
            //the root moving away means we assume network growth
            if(oldHopMa < firstHop.getMessageAge()){
                std::cout << "root moved away\n";
                int maDiff = firstHop.getMessageAge() - oldHopMa;
                //this means we have to increase every message age and add the new root
                for(Bridge &b : bridges)
                    b.setMessageAge(b.getMessageAge() + maDiff);
                bridges.push_back(root);
            }else{
                clearAndAdd(firstHop, root);
            }
        }else{
            //entirely new setup
            clearAndAdd(firstHop, root);
        }
    }
    hadTC = tc;

    Json::FastWriter writer;
    Json::Value toSend;
    toSend["messagetype"] = "push";
    Json::Value jsonBridges = Json::arrayValue;
    for(Bridge b : bridges)
        jsonBridges.append(b.toJson());
    toSend["bridges"] = jsonBridges;
    output << "sniffer is sending: " << std::endl << writer.write(toSend) << std::endl;
    try{
        if(client)
            client->send(toSend);
    }catch(const char * msg){
        output << msg << std::endl;
    }
}
BOOL DatabaseModule_Impl::sqlInsertMessage(IN MessageEntity& msg)
{
	if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState()
		|| MESSAGE_RENDERTYPE_SYSTEMTIPS == msg.msgRenderType)
	{
		return FALSE;
	}
	if (msg.msgId <= 0)
	{
		std::string msgDecrptyCnt;
		DECRYPT_MSG(msg.content, msgDecrptyCnt);
		LOG__(ERR, _T("msgid <= 0, msgid:%d msg_content:%s Don't save to DB!")
			, msg.msgId, util::stringToCString(msgDecrptyCnt));
		return FALSE;
	}

	try
	{
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertMessageSql.c_str());
		stmt.bind(1, (Int32)msg.msgId);
		stmt.bind(2, msg.sessionId.c_str());
		stmt.bind(3, msg.talkerSid.c_str());
		//对语音消息做个特殊处理,content存储的是json格式字符串
		if (MESSAGE_RENDERTYPE_AUDIO == msg.msgRenderType)
		{
			Json::Value root;
			root["msgAudioTime"] = msg.msgAudioTime;
			root["msgAudioId"] = msg.content;
			Json::FastWriter fstWrite;
			std::string audioContent = fstWrite.write(root);
			stmt.bind(4, audioContent.c_str());
		}
		else
		{
			stmt.bind(4, msg.content.c_str());
		}
		stmt.bind(5, msg.msgRenderType);
		stmt.bind(6, msg.msgSessionType);
		stmt.bind(7, (Int32)msg.msgTime);
		stmt.bind(8, time(0));
		stmt.execDML();
	}

	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		//MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		_msgToTrace(msg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		_msgToTrace(msg);
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 9
0
DWORD WINAPI CProcessMgr::RunInServerThread( LPVOID lpParameter )
{
	CProcessMgr* pMgr = (CProcessMgr*)lpParameter;

	std::string strXpdl = (LPCTSTR)pMgr->m_sXpdlStreamWithFileid;
	ZTools::MBToUTF8(strXpdl);
	CCustomXpdl xpdlObj;
	xpdlObj.LoadStream(strXpdl.c_str(), pMgr->m_sWorkPath + "\\temp.xml");
	xpdlObj.Parse();
	xpdlObj.UploadFileAndReplacePath();
	strXpdl.clear();
	xpdlObj.GetXpdlStream(strXpdl);

	// 	//pkgid
	// 	//xpdlFileContent
	// 	//ip
	// 	//userid
	// 	//username
	Json::Value jsonParams(Json::arrayValue);

	if (pMgr->m_bIsModelRun)
	{
		CString sPkgId;
		if (theApp.m_pBarJianmoTree)
		{
			CCxStructTreeNodeFlow* pRoot = (CCxStructTreeNodeFlow*)theApp.m_pBarJianmoTree->m_wndGridTree.m_StructTree.GetRoot();
			if (pRoot)
			{
				sPkgId = pRoot->m_strPkgId;
			}
		}
		jsonParams.append(Json::Value(sPkgId));
	}
	else
	{
		jsonParams.append(Json::Value(""));
	}
	jsonParams.append(Json::Value(strXpdl));

	jsonParams.append(Json::Value(GetLocalIpFromIce()));
	jsonParams.append(Json::Value(theApp.m_LoginData.m_strUser));
	jsonParams.append(Json::Value(theApp.m_LoginData.m_strRealName));
	if (pMgr->m_bIsModelRun)
	{
		jsonParams.append(Json::Value("Process"));
	}
	else
	{
		jsonParams.append(Json::Value("SubFlow"));
	}

	{
		int nPos = theApp.m_LoginData.m_strTicket.Find('=');
		if (nPos == -1)
		{
			jsonParams.append(Json::Value(""));
		}
		else
		{
			CString strTicket;
			strTicket = theApp.m_LoginData.m_strTicket.Right(theApp.m_LoginData.m_strTicket.GetLength() - theApp.m_LoginData.m_strTicket.Find('=') - 1);
			jsonParams.append(Json::Value(strTicket));
		}
	}
	Json::FastWriter writer;
	std::string strJsonParams = writer.write(jsonParams);

	if (!InvokeRunProcess(lpParameter, strJsonParams))
	{
		pMgr->ClearRunVar();
		HideLoading();
		return FALSE;
	}
	
	if (pMgr->m_bIsModelRun)
	{
		HideLoading();
		OpenRunInNewTab(lpParameter);
	}
	else
	{
		HideLoading();
		OpenRunInModal(lpParameter);
	}

	return TRUE;
}
Ejemplo n.º 10
0
std::string
statistics_collector::all_services_json() {
	boost::mutex::scoped_lock lock(mutex_);

	Json::FastWriter writer;
	Json::Value root;

	// cache info
	Json::Value cache_info;
	cache_info["1 - max cache size"] = (unsigned int)config()->max_message_cache_size();
	cache_info["2 - used bytes"] = (unsigned int)used_cache_size_;
	cache_info["3 - free bytes"] = (unsigned int)(config()->max_message_cache_size() - used_cache_size_);
	root["1 - cache info"] = cache_info;

	// queues totals info
	size_t total_queued_messages = 0;
	size_t total_unhandled_messages = 0;

	Json::Value messages_statistics;
	typedef configuration::services_list_t slist_t;
	const slist_t& services = config()->services_list();

	// get unhandled messages total
	slist_t::const_iterator services_it = services.begin();
	for (; services_it != services.end(); ++services_it) {

		// get service stats
		services_stats_t::iterator service_stat_it = services_stats_.find(services_it->second.name_);
		if (service_stat_it != services_stats_.end()) {
			std::map<std::string, size_t>& umsgs = service_stat_it->second.unhandled_messages;

			// unhandled messages
			std::map<std::string, size_t>::iterator uit = umsgs.begin();
			for (; uit != umsgs.end(); ++uit) {
				total_unhandled_messages += uit->second;
			}
		}
	}
	messages_statistics["1 - queued"] = (unsigned int)total_queued_messages;
	messages_statistics["2 - unhandled"] = (unsigned int)total_unhandled_messages;
	root["2 - messages statistics"] = messages_statistics;

	// services
	services_it = services.begin();
	for (; services_it != services.end(); ++services_it) {
		Json::Value service_info;
		service_info["1 - cocaine app"] = services_it->second.app_name_;
		service_info["2 - instance"] = services_it->second.instance_;
		service_info["3 - description"] = services_it->second.description_;
		service_info["4 - control port"] = services_it->second.hosts_url_;
		service_info["5 - hosts url"] = services_it->second.hosts_url_;

		// get service stats
		services_stats_t::iterator service_stat_it = services_stats_.find(services_it->second.name_);
		if (service_stat_it != services_stats_.end()) {
			// get references
			std::map<LT::ip_addr, std::string>& hosts = service_stat_it->second.hosts;
			std::map<std::string, size_t>& umsgs = service_stat_it->second.unhandled_messages;
			std::vector<std::string>& handles = service_stat_it->second.handles;

			// unhandled messages
			size_t unhandled_count = 0;
			std::map<std::string, size_t>::iterator uit = umsgs.begin();
			for (; uit != umsgs.end(); ++uit) {
				unhandled_count += uit->second;
			}
			service_info["6 - unhandled messages count"] = (unsigned int)unhandled_count;

			// service handles
			if (handles.empty()) {
				service_info["7 - handles"] = "no handles";
			}
			else {
				Json::Value service_handles;

				for (size_t i = 0; i < handles.size(); ++i) {

					// get handle statistics
					std::pair<std::string, std::string> stat_key(services_it->second.name_, handles[i]);
					handle_stats_t::iterator handle_it = handles_stats_.find(stat_key);

					if (handle_it != handles_stats_.end()) {
						Json::Value handle_info;

						handle_info["01 - queue pending"] = (unsigned int)handle_it->second.queue_status.pending;
						handle_info["02 - queue sent"] = (unsigned int)handle_it->second.queue_status.sent;
						handle_info["03 - overall sent"] = (unsigned int)handle_it->second.sent_messages;
						handle_info["04 - resent"] = (unsigned int)handle_it->second.resent_messages;
						handle_info["05 - bad sent"] = (unsigned int)handle_it->second.bad_sent_messages;
						handle_info["06 - timedout"] = (unsigned int)handle_it->second.timedout_responces;
						handle_info["07 - all responces"] = (unsigned int)handle_it->second.all_responces;
						handle_info["08 - good responces"] = (unsigned int)handle_it->second.normal_responces;
						handle_info["09 - err responces"] = (unsigned int)handle_it->second.err_responces;
						handle_info["10 - expired"] = (unsigned int)handle_it->second.expired_responses;

						service_handles[handles[i]] = handle_info;
					}
					else {
						service_handles[handles[i]] = "no handle statistics";
					}
				}

				service_info["7 - handles"] = service_handles;
			}

			// active hosts list
			if (hosts.empty()){
				service_info["8 - active hosts"] = "no hosts";
			}
			else {
				Json::Value service_hosts;
				std::map<LT::ip_addr, std::string>::iterator hosts_it = hosts.begin();
				size_t counter = 1;
				for (; hosts_it != hosts.end(); ++hosts_it) {
					std::string key = "host " + boost::lexical_cast<std::string>(counter);
					std::string value = host_info<LT>::string_from_ip(hosts_it->first);
					value += "(" + hosts_it->second + ")";
					service_hosts[key] = value;
					++counter;
				}

				service_info["8 - active hosts"] = service_hosts;
			}
		}

		Json::Value service;
		service[services_it->first] = service_info;
		root["3 - services"] = service;
	}

	return writer.write(root);
}
	void CloudScheduleTaskLoop::refreshKpiInfo()
	{
		bmco_debug(theLogger, "refreshKpiInfo()");
		
		MetaKPIInfoOp *tmpKPIPtr = NULL;
		std::vector<MetaKPIInfo> vecKPIInfo;
		tmpKPIPtr = dynamic_cast<MetaKPIInfoOp*>(ctlOper->getObjectPtr(MetaKPIInfoOp::getObjName()));

		if (!tmpKPIPtr->getAllKPIInfo(vecKPIInfo))
		{
			bmco_error(theLogger, "Failed to execute getAllKPIInfo on MetaShmKPIInfoTable");
		}

		std::string cloudKPIStr;
		std::string KPIInfoPath = ZNODE_ZOOKEEPER_STATUS_KPI + "/bol/" + g_sessionData.getBolName();
		
		try
		{
			if (!CloudDatabaseHandler::instance()->nodeExist(KPIInfoPath))
			{
				if (!CloudDatabaseHandler::instance()->createNode(KPIInfoPath, ZOO_EPHEMERAL))
				{
					bmco_error_f3(theLogger, "%s|%s|Faild to createNode: %s", 
						std::string("0"), std::string(__FUNCTION__), KPIInfoPath);
					return;
				}
			}

			Json::Value root(Json::objectValue);
			Json::Value field(Json::objectValue);
			Json::Value record(Json::arrayValue);

			Bmco::Timestamp now;
			LocalDateTime dtNow(now);
			std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);

			MetaBolInfo::Ptr ptr = new MetaBolInfo(BOL_NORMAL, "", "");
			MetaBolInfoOp *p = dynamic_cast<MetaBolInfoOp *>(
				   ctlOper->getObjectPtr(MetaBolInfoOp::getObjName()));
			if (!p->Query(ptr))
			{
				bmco_error(theLogger, "Failed to query MetaBolInfo definition.");
				return;
			}

			// 第一行存放本BOL的状态指标
			BolStatus status = ptr->status;
			std::string bolName = g_sessionData.getBolName();
			std::string subsys = g_sessionData.getsetSubSys();
			std::string domainName = g_sessionData.getDomainName();
			
			field["kpi_id"] = "指标编号";
			field["seq_no"] = "bol名称";
			field["bol_name"] = "bol名称";
			field["kpi_value"] = "指标值";
			field["kpi_value2"] = "指标值2";
			field["status_time"] = "变更时间";

			Json::Value array(Json::objectValue);
			array["kpi_id"] = std::string("1001");
			array["seq_no"] = bolName;
			array["bol_name"] = bolName;
			array["kpi_value"] = Bmco::format("%?d", Bmco::UInt32(status));
			array["kpi_value2"] = "";
			array["status_time"] = stNow;
			record[0] = array;

			for (int i = 0; i < vecKPIInfo.size(); i++)
			{
				if (1003 != vecKPIInfo[i].KPI_ID)
				{
					continue;
				}
				
				LocalDateTime dt(vecKPIInfo[i].Create_date);
				std::string stCreateTime = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
		 		dt = vecKPIInfo[i].Modi_date;
	    		std::string stModityTime = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);

				Json::Value array(Json::objectValue);
				array["kpi_id"] = Bmco::format("%?d", vecKPIInfo[i].KPI_ID);
				array["seq_no"] = std::string(vecKPIInfo[i].Seq_No.c_str());
				array["bol_name"] = std::string(vecKPIInfo[i].Bol_Cloud_Name.c_str());
				array["kpi_value"] = std::string(vecKPIInfo[i].KPI_Value.c_str());
				array["kpi_value2"] = std::string("");
				array["status_time"] = stModityTime;
				record[i+1] = array;
			}

			root["name"] = "c_info_kpi";
			root["desc"] = "指标信息";
			root["field"] = field;
			root["record"] = record;

			Json::FastWriter jfw;
			std::string oss = jfw.write(root);
			if (!CloudDatabaseHandler::instance()->setNodeData(KPIInfoPath, oss))
			{
				bmco_error(theLogger, "Faild to write KPIInfo");
			}
		}
		catch (boost::bad_lexical_cast &e)  
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(Bmco::Exception &e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
			return;
		}
		catch(std::exception& e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(...)
		{
			bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
									std::string("0"),std::string(__FUNCTION__));
			return;
		}
	}
	void CloudScheduleTaskLoop::refreshBpcbInfo()
	{
		std::vector<MetaBpcbInfo> vBpcbInfo;
		MetaBpcbInfoOp *p = dynamic_cast<MetaBpcbInfoOp *>(
		      ctlOper->getObjectPtr(MetaBpcbInfoOp::getObjName()));
		if (!p->getAllBpcbInfo(vBpcbInfo))
		{
			bmco_error_f2(theLogger, "%s|%s|Fail to getAllBpcbInfo", 
				std::string("0"),std::string(__FUNCTION__));
			return;
		}
		
		std::string cloudStatusStr;
		std::string bpcbInfoPath = ZNODE_ZOOKEEPER_STATUS_BPCB + "/" + g_sessionData.getBolName();

		try
		{
			if (!CloudDatabaseHandler::instance()->nodeExist(bpcbInfoPath))
			{
				if (!CloudDatabaseHandler::instance()->createNode(bpcbInfoPath, ZOO_EPHEMERAL))
				{
					bmco_error_f3(theLogger, "%s|%s|Faild to createNode %s", 
						std::string("0"), std::string(__FUNCTION__), bpcbInfoPath);
					return;
				}
			}

			Json::Value root(Json::objectValue);
			Json::Value field(Json::objectValue);
			Json::Value record(Json::arrayValue);

			std::string bolName = g_sessionData.getBolName();

			Bmco::Timestamp now;
			LocalDateTime dtNow(now);
			std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);
			
			field["bpcb_id"] = "bpcbid";
			field["sys_pid"] = "系统进程ID";
			field["program_id"] = "程序ID";
			field["create_date"] = "调度启动时间";
			field["heart_beat"] = "心跳时间";
			field["status"] = "进程状态";
			field["fd_limitation"] = "打开文件限制数";
			field["fd_inusing"] = "已打开文件数";
			field["cpu"] = "cpu使用率";
			field["ram"] = "RAM使用数";
			field["flow_id"] = "所属流程ID";
			field["instance_id"] = "实例ID";
			field["task_source"] = "任务来源";
			field["source_id"] = "来源ID";
			field["snapshot"] = "snapshot标志位";
			field["action_flag"] = "action";
			field["bol_name"] = "bolname";
			field["status_time"] = "状态变更时间";

			for (int i = 0; i < vBpcbInfo.size(); i++)
			{
				LocalDateTime dt(vBpcbInfo[i].m_tHeartBeat);
				std::string stHeartBeat = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
		 		dt = vBpcbInfo[i].m_tCreateTime;
	    		std::string stCreateTime = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);

				Json::Value array(Json::objectValue);
				array["bpcb_id"] = Bmco::format("%?d", vBpcbInfo[i].m_iBpcbID);
				array["sys_pid"] = Bmco::format("%?d", vBpcbInfo[i].m_iSysPID);
				array["program_id"] = Bmco::format("%?d", vBpcbInfo[i].m_iProgramID);
				array["create_date"] = stCreateTime;
				array["heart_beat"] = stHeartBeat;
				array["status"] = Bmco::format("%?d", vBpcbInfo[i].m_iStatus);
				array["fd_limitation"] = Bmco::format("%?d", vBpcbInfo[i].m_iFDLimitation);
				array["fd_inusing"] = Bmco::format("%?d", vBpcbInfo[i].m_iFDInUsing);
				array["cpu"] = Bmco::format("%?d", vBpcbInfo[i].m_iCPU);
				array["ram"] = Bmco::format("%?d", vBpcbInfo[i].m_iRAM);
				array["flow_id"] = Bmco::format("%?d", vBpcbInfo[i].m_iFlowID);
				array["instance_id"] = Bmco::format("%?d", vBpcbInfo[i].m_iInstanceID);
				array["task_source"] = Bmco::format("%?d", vBpcbInfo[i].m_iTaskSource);
				array["source_id"] = Bmco::format("%?d", vBpcbInfo[i].m_iSourceID);
				array["snapshot"] = Bmco::format("%?d", vBpcbInfo[i].m_iSnapShot);
				array["action_flag"] = Bmco::format("%?d", vBpcbInfo[i].m_iAction);
				array["bol_name"] = bolName;
				array["status_time"] = stNow;
				record[i] = array;
			}

			root["name"] =  "c_info_bpcb";
			root["desc"] =  "bpcb信息";
			root["field"] = field;
			root["record"] = record;

			Json::FastWriter jfw;
			std::string oss = jfw.write(root);
			if (!CloudDatabaseHandler::instance()->setNodeData(bpcbInfoPath, oss))
			{
				bmco_error(theLogger, "Faild to write  MetaBpcbInfo");
			}
		}
		catch (boost::bad_lexical_cast &e)  
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(Bmco::Exception &e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
			return;
		}
		catch(std::exception& e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(...)
		{
			bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
									std::string("0"),std::string(__FUNCTION__));
			return;
		}
	}
	void CloudScheduleTaskLoop::refreshChunkInfo()
	{
		std::vector<MetaChunkInfo> vChunkInfo;
		MetaChunkInfoOp *p = dynamic_cast<MetaChunkInfoOp *>(
		      ctlOper->getObjectPtr(MetaChunkInfoOp::getObjName()));
		if (!p->Query(vChunkInfo))
		{
			bmco_error_f2(theLogger, "%s|%s|Fail to getAllChunkInfo", 
				std::string("0"),std::string(__FUNCTION__));
			return;
		}
		
		std::string cloudStatusStr;
		std::string chunkInfoPath = ZNODE_ZOOKEEPER_STATUS_CHUNK + "/" + g_sessionData.getBolName();

		try
		{
			if (!CloudDatabaseHandler::instance()->nodeExist(chunkInfoPath))
			{
				if (!CloudDatabaseHandler::instance()->createNode(chunkInfoPath, ZOO_EPHEMERAL))
				{
					bmco_error_f3(theLogger, "%s|%s|Faild to createNode %s", 
						std::string("0"), std::string(__FUNCTION__), chunkInfoPath);
					return;
				}
			}

			Json::Value root(Json::objectValue);
			Json::Value field(Json::objectValue);
			Json::Value record(Json::arrayValue);

			Bmco::Timestamp now;
			LocalDateTime dtNow(now);
			std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);

			field["chunk_id"] = "内存块号";
			field["used_size"] = "使用大小";
			field["status_time"] = "修改时间";
			field["bol_id"] = "BOLID";

			for (int i = 0; i < vChunkInfo.size(); i++)
			{
				Json::Value array(Json::objectValue);
				array["chunk_id"] = Bmco::format("%?d", vChunkInfo[i].id);
				array["used_size"] = Bmco::format("%?d", vChunkInfo[i].usedBytes);
				array["status_time"] = stNow;
				array["bol_id"] = 0;
				record[i] = array;
			}

			root["name"] = "c_info_chunk";
			root["desc"] = "chunk信息";
			root["field"] = field;
			root["record"] = record;

			Json::FastWriter jfw;
			std::string oss = jfw.write(root);
			if (!CloudDatabaseHandler::instance()->setNodeData(chunkInfoPath, oss))
			{
				bmco_error(theLogger, "Faild to write  MetaChunkInfo");
			}
		}
		catch (boost::bad_lexical_cast &e)  
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(Bmco::Exception &e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
			return;
		}
		catch(std::exception& e)
		{
			bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
			return;
		}
		catch(...)
		{
			bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
									std::string("0"),std::string(__FUNCTION__));
			return;
		}
	}
    /*
     * BarcodeScannerNDK::startRead
     *
     * This method is called to start a QR code read. A connection is opened to the device camera
     * and the photo viewfinder is started.
     */
    int BarcodeScannerNDK::startRead() {

        std::string errorEvent = "community.barcodescanner.errorfound.native";
        Json::FastWriter writer;
        Json::Value root;

        camera_error_t err;
        // Open the camera first before running any operations on it
        err = camera_open(CAMERA_UNIT_REAR,CAMERA_MODE_RW | CAMERA_MODE_ROLL,&mCameraHandle);
        if ( err != CAMERA_EOK){
#ifdef DEBUG
            fprintf(stderr, " Ran into an issue when initializing the camera = %d\n ", err);
#endif
            root["state"] = "Open Camera";
            root["error"] = err;
            root["description"] = getCameraErrorDesc( err );
            m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
            return EIO;
        }

        // We want maximum framerate from the viewfinder which will scan for codes
        int numRates = 0;
		err = camera_get_photo_vf_framerates(mCameraHandle, true, 0, &numRates, NULL, NULL);
		double* camFramerates = new double[numRates];
		bool maxmin = false;
		err = camera_get_photo_vf_framerates(mCameraHandle, true, numRates, &numRates, camFramerates, &maxmin);

		// QC8960 doesn't allow for changing the rotation, so we'll just take note of it here and rotate later.
		uint32_t* rotations = new uint32_t[8];
		int numRotations = 0;
		bool nonsquare = false;
		err = camera_get_photo_rotations(mCameraHandle, CAMERA_FRAMETYPE_JPEG, true, 8, &numRotations, rotations, &nonsquare);
		rotation = rotations[0] / 90;

		// We're going to turn on burst mode for the camera and set maximum framerate for the viewfinder
		err = camera_set_photovf_property(mCameraHandle,
			CAMERA_IMGPROP_BURSTMODE, 1,
			CAMERA_IMGPROP_FRAMERATE, camFramerates[0]);
		if ( err != CAMERA_EOK){
#ifdef DEBUG
			fprintf(stderr, " Ran into an issue when configuring the camera viewfinder = %d\n ", err);
#endif
			root["state"] = "Set VF Props";
			root["error"] = err;
			root["description"] = getCameraErrorDesc( err );
			m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
			return EIO;
		}

		// The actual camera will get frames at a slower rate than the viewfinder
		err = camera_set_photo_property(mCameraHandle,
			CAMERA_IMGPROP_BURSTDIVISOR, (double) 3.0);
		if ( err != CAMERA_EOK){
#ifdef DEBUG
			fprintf(stderr, " Ran into an issue when configuring the camera properties = %d\n ", err);
#endif
			root["state"] = "Set Cam Props";
			root["error"] = err;
			root["description"] = getCameraErrorDesc( err );
			m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
			return EIO;
		}

		// Starting viewfinder up which will call the viewfinder callback - this gets the NV12 images for scanning
        err = camera_start_photo_viewfinder( mCameraHandle, &viewfinder_callback, NULL, NULL);
        if ( err != CAMERA_EOK) {
#ifdef DEBUG
            fprintf(stderr, "Ran into a strange issue when starting up the camera viewfinder\n");
#endif
            root["state"] = "ViewFinder Start";
            root["error"] = err;
            root["description"] = getCameraErrorDesc( err );
            m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
            return EIO;
        }

        // Focus mode can't be set until the viewfinder is started. We need Continuous Macro for barcodes
        err = camera_set_focus_mode(mCameraHandle, CAMERA_FOCUSMODE_CONTINUOUS_MACRO);
		if ( err != CAMERA_EOK){
#ifdef DEBUG
			fprintf(stderr, " Ran into an issue when setting focus mode = %d\n ", err);
#endif
			root["state"] = "Set Focus Mode";
			root["error"] = err;
			root["description"] =  getCameraErrorDesc( err );
			m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
			return EIO;
		}

		// Now start capturing burst frames in JPEG format for sending to the front end.
		err = camera_start_burst(mCameraHandle, NULL, NULL, NULL, &image_callback, NULL);
		if ( err != CAMERA_EOK) {
#ifdef DEBUG
			fprintf(stderr, "Ran into an issue when starting up the camera in burst mode\n");
#endif
			root["state"] = "Start Camera Burst";
			root["error"] = err;
			root["description"] = getCameraErrorDesc( err );
			m_pParent->NotifyEvent(errorEvent + " " + writer.write(root));
			return EIO;
		}

        std::string successEvent = "community.barcodescanner.started.native";
        root["successful"] = true;
        m_pParent->NotifyEvent(successEvent + " " + writer.write(root));
        return EOK;
    }
    /*
     * image_callback
     *
     * handles the burst frames from the camera, which are standard JPEG images.
     * These will be sent to the front end for display.
     */
    void image_callback(camera_handle_t handle,camera_buffer_t* buf,void* arg) {

       	if (buf->frametype == CAMERA_FRAMETYPE_JPEG) {
			fprintf(stderr, "still image size: %lld\n", buf->framedesc.jpeg.bufsize);

			Json::FastWriter writer;
			Json::Value root;

			// saving temporary files barcode0.jpg to barcode9.jpg
			std::string tempFileName = "barcode" + convertIntToString(filecounter) + ".jpg";
			if (++filecounter >=10) {
				filecounter = 0;
			}
			// saving in the /tmp directory of the application which gets cleaned out when the app exits
			std::string tempFilePath = std::string(getcwd(NULL, 0)) + "/" + TMP_PATH + tempFileName;
			FILE* fp = fopen(tempFilePath.c_str(), "wb");
			if (fp!= NULL) {
				fwrite((const unsigned char *)buf->framebuf, buf->framedesc.jpeg.bufsize, 1, fp);
				fclose(fp);
			}

			// QC8960 based devices create jpegs with exif orientation and need rotating
			// We'll also scale down as much as possible to reduce file size.
			img_lib_t ilib;
			int rc;
			if ((rc = img_lib_attach(&ilib)) != IMG_ERR_OK) {
				fprintf(stderr, "img_lib_attach() failed: %d\n", rc);
			}

			img_t img;
			if (rotation == 0 || rotation == 2) {
				img.w = 240;
				img.flags = IMG_W;
			} else {
				img.h = 240;
				img.flags = IMG_H;
			}
			int resizeResult = img_load_resize_file( ilib, tempFilePath.c_str(), NULL, &img );
			img_t dst;
			img_fixed_t angle = 0;
			switch (rotation) {
			case 1:
				angle = IMG_ANGLE_90CCW;
				break;
			case 2:
				angle = IMG_ANGLE_180;
				break;
			case 3:
				angle = IMG_ANGLE_90CW;
				break;
			default:
				break;
			}
			if (angle != 0) {
				int err = img_rotate_ortho(&img, &dst, angle);
			} else {
				dst = img;
			}

			// Set quality of output
            dst.quality = 75;
            dst.flags = dst.flags | IMG_QUALITY;

			int writeResult = img_write_file( ilib, tempFilePath.c_str(), NULL, &dst );

			img_lib_detach(ilib);

			// Send the file path for loading in the front end since JNEXT only handles strings
			root["frame"]  = tempFilePath;
			std::string event = "community.barcodescanner.frameavailable.native";
			if ( eventDispatcher != NULL ){
				 eventDispatcher->NotifyEvent(event + " " + writer.write(root));
			}
       	}

    }
const std::string ResetGlobalPropertiesResponseMarshaller::toString(const ResetGlobalPropertiesResponse& e)
{
  Json::FastWriter writer;
  return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
Ejemplo n.º 17
0
void Socket::sendMessage(const Json::Value& message, bool addTerminator) {
	Json::FastWriter writer;
	string messageStr = writer.write(message);
	sendMessage(messageStr + (addTerminator ? MESSAGE_TERMINATOR : ""));
}
Ejemplo n.º 18
0
std::string GetJsonStringWithNoStyled(const Json::Value& values)
{
	Json::FastWriter fw;
	return fw.write(values);
}
const std::string AppInterfaceUnregisteredReasonMarshaller::toString(const AppInterfaceUnregisteredReason& e)
{
  Json::FastWriter writer;
  return e.mInternal==AppInterfaceUnregisteredReason::INVALID_ENUM ? "" : writer.write(toJSON(e));

}
Ejemplo n.º 20
0
const std::string PermissionItemMarshaller::toString(const PermissionItem& e)
{
  Json::FastWriter writer;
  return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
BOOL DatabaseModule_Impl::sqlBatchInsertMessage(IN std::list<MessageEntity>& msgList)
{
	if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState())
	{
		LOG__(ERR, _T("TCPCLIENT_STATE_DISCONNECT"));
		return FALSE;
	}
	if (msgList.empty())
	{
		LOG__(ERR, _T("msgList is empty!"));
		return FALSE;
	}
	MessageEntity msg;
	try
	{
		CppSQLite3Statement stmtBegin = m_pSqliteDB->compileStatement(BeginInsert.c_str());
		stmtBegin.execDML();

		std::list<MessageEntity>::iterator iter = msgList.begin();
		for (; iter != msgList.end(); ++iter)
		{
			MessageEntity msg = *iter;
			if (msg.msgId <= 0)//非法的msg消息不用存储
			{
				std::string msgDecrptyCnt;
				DECRYPT_MSG(msg.content,msgDecrptyCnt);
				LOG__(ERR, _T("msgid <= 0, msgid:%d msg_content:%s Don't save to DB!")
					, msg.msgId, util::stringToCString(msgDecrptyCnt));
				continue;
			}
			CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertMessageSql.c_str());
			stmt.bind(1, (Int32)msg.msgId);
			stmt.bind(2, msg.sessionId.c_str());
			stmt.bind(3, msg.talkerSid.c_str());
			//对语音消息做个特殊处理,content存储的是json格式字符串
			if (MESSAGE_RENDERTYPE_AUDIO == msg.msgRenderType)
			{
				Json::Value root;
				root["msgAudioTime"] = msg.msgAudioTime;
				root["msgAudioId"] = msg.content;
				Json::FastWriter fstWrite;
				std::string audioContent = fstWrite.write(root);
				stmt.bind(4, audioContent.c_str());
			}
			else
			{
				stmt.bind(4, msg.content.c_str());
			}
			stmt.bind(5, msg.msgRenderType);
			stmt.bind(6, msg.msgSessionType);
			stmt.bind(7, (Int32)msg.msgTime);
			stmt.bind(8, time(0));
			stmt.execDML();
		}

		CppSQLite3Statement stmtEnd = m_pSqliteDB->compileStatement(EndInsert.c_str());
		stmtEnd.execDML();
	}
	catch (CppSQLite3Exception& e)
	{
		CString csErrMsg = util::stringToCString(e.errorMessage());
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		CppSQLite3Statement stmtRollback = m_pSqliteDB->compileStatement(RollBack.c_str());
		stmtRollback.execDML();
		_msgToTrace(msg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		_msgToTrace(msg);
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 22
0
int main(int argc, char **argv) {
	int exit_ret = 0;

	Json::Rpc::TcpClient tcpClient(std::string("127.0.0.1"), 7500);
	Json::Value query;
	Json::Value params;
	Json::FastWriter writer;
	std::string queryStr;
	std::string responseStr;

	/* avoid compilation warnings */
	argc = argc;
	argv = argv;

	if(!networking::init())
	{
		std::cerr << "Networking initialization failed" << std::endl;
		exit(EXIT_FAILURE);
	}

	if(!tcpClient.Connect())
	{
		std::cerr << "Cannot connect to remote peer!" << std::endl;
		exit(EXIT_FAILURE);
	}

	/* build JSON-RPC query */
	query["jsonrpc"] = "2.0";
	query["id"] = 1;
	query["method"] = "nui_workflow_quit";

	//params["index"] = 3;

	//query["params"] = params;

	queryStr = writer.write(query);
	std::cout << "Query is: " << queryStr << std::endl;

	if(tcpClient.Send(queryStr) == -1)
	{
		std::cerr << "Error while sending data!" << std::endl;
		exit(EXIT_FAILURE);
	}

	/* wait the response */
	if(tcpClient.Recv(responseStr) != -1)
	{
		std::cout << "Received: " << responseStr << std::endl;
	}
	else
	{
		std::cerr << "Error while receiving data!" << std::endl;
	}


exit_standard:
	tcpClient.Close();
	networking::cleanup();
	return exit_ret;

exit_critical:
	exit_ret = 1;
	printf("%s", "critical exit");
	goto exit_standard;
}
void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
	// Clear saved lamps.
	lights.clear();
	// Use json parser to parse reponse.
	Json::Reader reader;
	Json::FastWriter writer;
	// Read light ids if none have been supplied by the user.
	if (lightIds.size() != nLights) {
		lightIds.clear();
		//
		QByteArray response = get("lights");
		Json::Value json;
		if (!reader.parse(QString(response).toStdString(), json)) {
			throw std::runtime_error(("No lights found at " + getUrl("lights")).toStdString());
		}
		// Loop over all children.
		for (Json::ValueIterator it = json.begin(); it != json.end() && lightIds.size() < nLights; it++) {
			int lightId = atoi(it.key().asCString());
			lightIds.push_back(lightId);
			std::cout << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): found light with id " << lightId
					<< "." << std::endl;
		}
		// Check if we found enough lights.
		if (lightIds.size() != nLights) {
			throw std::runtime_error(("Not enough lights found at " + getUrl("lights")).toStdString());
		}
	}
	// Iterate lights.
	for (unsigned int i = 0; i < nLights; i++) {
		// Read the response.
		QByteArray response = get(getRoute(lightIds.at(i)));
		// Parse JSON.
		Json::Value json;
		if (!reader.parse(QString(response).toStdString(), json)) {
			// Error occured, break loop.
			std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got invalid response from light "
					<< getUrl(getRoute(lightIds.at(i))).toStdString() << "." << std::endl;
			break;
		}
		// Get state object values which are subject to change.
		Json::Value state(Json::objectValue);
		if (!json.isMember("state")) {
			std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got no state for light from "
					<< getUrl(getRoute(lightIds.at(i))).toStdString() << std::endl;
			break;
		}
		if (!json["state"].isMember("on")) {
			std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got no valid state from light "
					<< getUrl(getRoute(lightIds.at(i))).toStdString() << std::endl;
			break;
		}
		state["on"] = json["state"]["on"];
		if (json["state"]["on"] == true) {
			state["xy"] = json["state"]["xy"];
			state["bri"] = json["state"]["bri"];
		}
		// Determine the model id.
		QString modelId = QString(writer.write(json["modelid"]).c_str()).trimmed().replace("\"", "");
		QString originalState = QString(writer.write(state).c_str()).trimmed();
		// Save state object.
		lights.push_back(PhilipsHueLight(lightIds.at(i), originalState, modelId));
	}
}
Ejemplo n.º 24
0
 void Client::CallNotification(const std::string& name,
                               const Json::Value& parameter) throw(Exception)
 {
     Json::FastWriter writer;
     this->connector->SendMessage(writer.write(this->BuildRequestObject(name,parameter, -1)));
 }
Ejemplo n.º 25
0
const std::string ActionPerformerMarshaller::toString(const ActionPerformer& e)
{
  Json::FastWriter writer;
  return e.mInternal==ActionPerformer::INVALID_ENUM ? "" : writer.write(toJSON(e));

}
Ejemplo n.º 26
0
const std::string ButtonNameMarshaller::toString(const ButtonName& e)
{
  Json::FastWriter writer;
  return e.mInternal==ButtonName::INVALID_ENUM ? "" : writer.write(toJSON(e));

}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
	int thread_num;
	long request_num;
	int log_level;
	int connection_num;
	std::string start_event;
	std::string mpath, log;

	po::options_description desc("Allowed options");

	desc.add_options()
		("help,h", "this help message")
		("thread,t", po::value<int>(&thread_num)->default_value(10), "number of threads")
		("manifest,m", po::value<std::string>(&mpath), "manifest file")
		("log,l", po::value<std::string>(&log), "log file")
		("log-level,L", po::value<int>(&log_level)->default_value(2), "log level")
		("request,r", po::value<long>(&request_num)->default_value(1000000))
		("start-event,s", po::value<std::string>(&start_event), "starting event")
		("connections,c", po::value<int>(&connection_num)->default_value(1), "number of network connections")
		("run-io,i", "run io test instead of exec")
	;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) {
		std::cout << desc << std::endl;
		return -1;
	}

	if (!vm.count("manifest")) {
		std::cerr << "You must provide manifest path\n" << desc << std::endl;
		return -1;
	}

	if (!vm.count("start-event")) {
		std::cerr << "You must provide starting event path\n" << desc << std::endl;
		return -1;
	}

	bool run_io = vm.count("run-io") ? true : false; 

	Json::Reader reader;
	Json::Value root;

	std::ifstream min(mpath.c_str());
	reader.parse(min, root);

	if (vm.count("log"))
		root["args"]["config"]["log"] = log;
	if (vm.count("log-level"))
		root["args"]["config"]["log-level"] = log_level;

	grape::logger::instance()->init(root["args"]["config"]["log"].asString(), root["args"]["config"]["log-level"].asInt(), true);

	Json::FastWriter writer;
	std::string config = writer.write(root["args"]["config"]);

	pt::ptime time_start(pt::microsec_clock::local_time());
	{
		std::vector<boost::shared_ptr<starter> > proc;

		for (int i = 0; i < connection_num; ++i) {
			boost::shared_ptr<starter> start(new starter(root["args"]["config"], config,
						start_event, thread_num, request_num / connection_num, run_io));
			proc.push_back(start);
		}
	}
	pt::ptime time_end(pt::microsec_clock::local_time());

	pt::time_duration duration(time_end - time_start);

	std::cout << "Total time: " << duration << ", rps: " << request_num * 1000000 / duration.total_microseconds() << std::endl;

	return 0;
}
Ejemplo n.º 28
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:
		size_t JsonCount = root.size();
		Int64 Now = time(NULL);
		{
			cCSLock Lock(m_CSNameToUUID);
			for (size_t 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);
			}  // for idx - root[]
		}  // cCSLock (m_CSNameToUUID)
		
		// Also cache the UUIDToName:
		{
			cCSLock Lock(m_CSUUIDToName);
			for (size_t 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())
}
Ejemplo n.º 29
0
bool
heartbeats_collector_t::get_metainfo_from_endpoint(const inetv4_endpoint_t& endpoint,
												   std::string& response_t)
{
	// create req socket
	std::auto_ptr<zmq::socket_t> zmq_socket;
	zmq_socket.reset(new zmq::socket_t(*(context()->zmq_context()), ZMQ_REQ));
	std::string ex_err;

	// connect to host
	std::string host_ip_str = nutils::ipv4_to_str(endpoint.host.ip);
	std::string connection_str = "tcp://" + host_ip_str + ":";
	connection_str += boost::lexical_cast<std::string>(endpoint.port);

	int timeout = 0;
	zmq_socket->setsockopt(ZMQ_LINGER, &timeout, sizeof(timeout));
	zmq_socket->setsockopt(ZMQ_IDENTITY, m_uuid.c_str(), m_uuid.length());
	zmq_socket->connect(connection_str.c_str());

	// send request for cocaine metadata
	Json::Value msg(Json::objectValue);
	Json::FastWriter writer;

	msg["version"] = 2;
	msg["action"] = "info";

	std::string info_request = writer.write(msg);
	zmq::message_t message(info_request.length());
	memcpy((void *)message.data(), info_request.c_str(), info_request.length());

	bool sent_request_ok = true;

	try {
		sent_request_ok = zmq_socket->send(message);
	}
	catch (const std::exception& ex) {
		sent_request_ok = false;
		ex_err = ex.what();
	}

	if (!sent_request_ok) {
		// in case of bad send
		std::string error_msg = "heartbeats - could not send metadata request to endpoint: " + endpoint.as_string();
		log(PLOG_WARNING, error_msg + ex_err);

		return false;
	}

	// create polling structure
	zmq_pollitem_t poll_items[1];
	poll_items[0].socket = *zmq_socket;
	poll_items[0].fd = 0;
	poll_items[0].events = ZMQ_POLLIN;
	poll_items[0].revents = 0;

	// poll for responce
	int res = zmq_poll(poll_items, 1, host_socket_ping_timeout * 1000);
	if (res <= 0) {
		return false;
	}

	if ((ZMQ_POLLIN & poll_items[0].revents) != ZMQ_POLLIN) {
		return false;
	}

	// receive cocaine control data
	zmq::message_t reply;
	bool received_response_ok = true;

	try {
		received_response_ok = zmq_socket->recv(&reply);
		response_t = std::string(static_cast<char*>(reply.data()), reply.size());
	}
	catch (const std::exception& ex) {
		received_response_ok = false;
		ex_err = ex.what();
	}

	if (!received_response_ok) {
		std::string error_msg = "heartbeats - could not receive metadata response from endpoint: " + endpoint.as_string();
		log(PLOG_WARNING, error_msg + ex_err);

		return false;
	}

	return true;
}
Ejemplo n.º 30
0
const std::string GetSupportedLanguagesMarshaller::toString(const GetSupportedLanguages& e)
{
  Json::FastWriter writer;
  return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}