当前位置: 首页>>代码示例>>C++>>正文


C++ json::FastWriter类代码示例

本文整理汇总了C++中json::FastWriter的典型用法代码示例。如果您正苦于以下问题:C++ FastWriter类的具体用法?C++ FastWriter怎么用?C++ FastWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了FastWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: NowPlayingSetMetadata

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

      }
开发者ID:Jayapraju,项目名称:WebWorks-Community-APIs,代码行数:24,代码来源:NowPlaying_ndk.cpp

示例2: writeJsonCpp

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);
}
开发者ID:YarinYang,项目名称:cocos2d-x-test,代码行数:24,代码来源:HelloWorldScene.cpp

示例3: OnClicked

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;
}
开发者ID:netease-im,项目名称:NIM_PC_Demo,代码行数:24,代码来源:custom_msg_form.cpp

示例4: ApplyUserAttributes

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

         }
      }
   }
}
开发者ID:BlueBolt,项目名称:bb_arnoldAlembicProcedural,代码行数:100,代码来源:WriteOverrides.cpp

示例5: checkIntegrityConst

const std::string ScrollableMessageMarshaller::toString(const ScrollableMessage& e)
{
  Json::FastWriter writer;
  return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
开发者ID:Luxoft,项目名称:SDLP,代码行数:5,代码来源:ScrollableMessageMarshaller.cpp

示例6:

const std::string HMILevelMarshaller::toString(const HMILevel& e)
{
  Json::FastWriter writer;
  return e.mInternal==HMILevel::INVALID_ENUM ? "" : writer.write(toJSON(e));

}
开发者ID:Luxoft,项目名称:SDLP,代码行数:6,代码来源:HMILevelMarshaller.cpp

示例7: process_packet


//.........这里部分代码省略.........
    //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;
    }
}
开发者ID:alxshine,项目名称:stp-tree-generator,代码行数:101,代码来源:Sniffer.cpp

示例8: sqlInsertMessage

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;
}
开发者ID:0359xiaodong,项目名称:TeamTalk,代码行数:62,代码来源:DatabaseModule_MessageDB_Impl.cpp

示例9: RunInServerThread

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;
}
开发者ID:cugxiangzhenwei,项目名称:WorkPlatForm,代码行数:87,代码来源:ProcessMgr.cpp

示例10: lock

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";
					}
//.........这里部分代码省略.........
开发者ID:sguzwf,项目名称:lsd,代码行数:101,代码来源:statistics_collector.cpp

示例11: refreshKpiInfo

	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");
			}
//.........这里部分代码省略.........
开发者ID:lx317190991,项目名称:linux-cloud,代码行数:101,代码来源:CloudScheduleTaskLoop.cpp

示例12: refreshBpcbInfo

	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()));
//.........这里部分代码省略.........
开发者ID:lx317190991,项目名称:linux-cloud,代码行数:101,代码来源:CloudScheduleTaskLoop.cpp

示例13: refreshChunkInfo

	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;
		}
	}
开发者ID:lx317190991,项目名称:linux-cloud,代码行数:84,代码来源:CloudScheduleTaskLoop.cpp

示例14: startRead

    /*
     * 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");
//.........这里部分代码省略.........
开发者ID:Balgam,项目名称:WebWorks-Community-APIs,代码行数:101,代码来源:barcodescanner_ndk.cpp

示例15: image_callback

    /*
     * 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));
			}
       	}

    }
开发者ID:Balgam,项目名称:WebWorks-Community-APIs,代码行数:82,代码来源:barcodescanner_ndk.cpp


注:本文中的json::FastWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。