Exemplo n.º 1
0
void AsyncHttpRequest::BeginDelete(std::string path, Json::Value reqData,
                                   std::function<void(std::string)>&& Callback) {
    _callback = Callback;

    Json::FastWriter writer;

    std::string paramstr = writer.write(reqData);
    tcp::resolver::query	query(_hostname, "http");

    std::ostream request_stream(&_request);
    request_stream << "DELETE " << path << " HTTP/1.1\r\n";
    request_stream << "Host: " << _hostname << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n";
    request_stream << "Content-Length: " << paramstr.size() << "\r\n\r\n";
    request_stream << paramstr;

    _resolver.async_resolve(query,
                            std::bind(&AsyncHttpRequest::handle_resolve,
                                      shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
// 获取待发送的数据,可先获取data长度,如:GetSendData(NULL, 0, dataLen);
bool UploadPopLadyAutoInviteTask::GetSendData(void* data, unsigned int dataSize, unsigned int& dataLen)
{
	bool result = false;
	
	// 构造json协议
	Json::Value root;
	root[TARGETID_PARAM] = m_userId;
	root[MSGID_PARAM] = m_msg;
	root[KEY_PARAM] = atof(m_key.c_str());
	Json::FastWriter writer;
	string json = writer.write(root);
	
	// 填入buffer
	if (json.length() < dataSize) {
		memcpy(data, json.c_str(), json.length());
		dataLen = json.length();

		result  = true;
	}
	return result;
}
int WriteToFile()
{
    using namespace std;
    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);


    ofstream ofs;
    ofs.open("test1.json");
    assert(ofs.is_open());
    ofs << json_file;

    return 0;
}
Exemplo n.º 4
0
int SignalQuality(Json::Value& response)
{
    if(!g_current_livestream.empty())
    {
        Json::FastWriter writer;
        std::string arguments = writer.write(g_current_livestream);

        int retval = ArgusTVJSONRPC("ArgusTV/Control/GetLiveStreamTuningDetails", arguments, response);

        //if (retval != E_FAILED)
        //{
        //  printValueTree(response);
        //}

        return retval;
    }
    else
    {
        return E_FAILED;
    }
}
// 初始化参数
bool SendCamShareInviteTask::InitParam(const string& userId, CamshareInviteType inviteType, int sessionId, const string& fromName)
{
	bool result = false;
	if (!userId.empty()) {
		m_userId = userId;
        
        Json::Value root;
        root[CamshareInviteTypeKey] = inviteType;
        root[CamshareInviteTypeSessionIdKey] = sessionId;
        root[CamshareInviteTypeFromNameKey] = fromName;
        
        Json::FastWriter writer;
        string camShareMsg = writer.write(root);
        
        m_camShareMsg = camShareMsg;
        
		result = true;
	}
	
	return result;
}
Exemplo n.º 6
0
int SocketIO::write(const Json::Value &data, const string& key){
	Json::FastWriter writer;
	string msg = writer.write(data);
	uint32_t len = htonl(msg.length());
	string hmac_key;

	hmac_msje(key, msg, hmac_key);

	if(send(this->fd, (void*) &len, 4, 0) != 4)
		return -1;

	if ((uint32_t) send(this->fd,
			(void*) msg.c_str(), msg.length(), 0) != msg.length())
		return -1;

	if ((uint32_t) send(this->fd,
			(void*) hmac_key.c_str(), hmac_key.length(), 0) != hmac_key.length())
		return -1;

	return 0;
}
Exemplo n.º 7
0
bool CLibrary::queryByISBN(const char * strISBN, IBook ** ppBook)
{
	std::string strRequest;
	std::string strRespond;
	Json::Value value0;
	value0["command"] = "library_queryByISBN";
	value0["isbn"] = strISBN;
	Json::FastWriter writer;
	strRequest = writer.write(value0);
	if (sendRequest(strRequest, strRespond)) {
		Json::Reader reader;
		Json::Value value;
		reader.parse(strRespond, value);
		if (value["result"].asString() == "1") {
			TBookBasicInfo *Info = new TBookBasicInfo;
			Info->id = value["id"].asInt();
			Info->count = value["count"].asInt();
			Info->bcount = value["bcount"].asInt();
			Info->name = value["name"].asString();
			Info->author = value["author"].asString();
			Info->isbn = value["isbn"].asString();
			Info->publisher = value["publisher"].asString();
			CBook *book = new CBook();
			book->m_CBBI = Info;
			book->id = Info->id;
			book->AddRef();
			*ppBook = book;
			return true;
		}
		else
		{
			if (value["result"].asString() == "DatabaseError")
				setError(DatabaseError, 0, "database_error");
			else setError(InvalidParam, 1, "Invalid strISBN");//jere w about 1
			return false;
		}
	}
	else setError(NetworkError, 0, "network_error");
	return false;
}
Exemplo n.º 8
0
int CLibrary::queryByName(const char * strName, IFvector& vBooks, int nCount, int nTop)
{
	std::string strRequest;
	std::string strRespond;
	Json::Value value0;
	value0["command"] = "library_queryByName";
	value0["name"] = strName;
	value0["nCount"] = nCount;
	value0["nTop"] = nTop;
	Json::FastWriter writer;
	strRequest = writer.write(value0);
	if (!sendRequest(strRequest, strRespond))
	{
		setError(NetworkError, 0, "Network Error");
		return -1;
	}
	Json::Reader reader;
	Json::Value value;
	reader.parse(strRespond, value);

	int num = value[0].asInt();
	for (int i = 0; i < num; i++) {
		TBookBasicInfo Info;
		Json::Value bookinfo = value[i + 1];
		Info.id = bookinfo["id"].asInt();
		Info.count = bookinfo["count"].asInt();
		Info.bcount = bookinfo["bcount"].asInt();
		Info.name = bookinfo["name"].asString();
		Info.author = bookinfo["author"].asString();
		Info.isbn = bookinfo["isbn"].asString();
		Info.publisher = bookinfo["publisher"].asString();;
		CBook *book = new CBook;
		TBookBasicInfo *pInfo = new TBookBasicInfo(Info);
		book->m_CBBI = pInfo;
		book->id = Info.id;
		//book->setBasicInfo(Info);
		vBooks.push_back(book);
	}
	return 	num;
}
Exemplo n.º 9
0
void cProtocol_1_11_0::HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer)
{
	cServer * Server = cRoot::Get()->GetServer();
	AString ServerDescription = Server->GetDescription();
	auto NumPlayers = static_cast<signed>(Server->GetNumPlayers());
	auto MaxPlayers = static_cast<signed>(Server->GetMaxPlayers());
	AString Favicon = Server->GetFaviconData();
	cRoot::Get()->GetPluginManager()->CallHookServerPing(*m_Client, ServerDescription, NumPlayers, MaxPlayers, Favicon);

	// Version:
	Json::Value Version;
	Version["name"] = "Cuberite 1.11";
	Version["protocol"] = cProtocolRecognizer::PROTO_VERSION_1_11_0;

	// Players:
	Json::Value Players;
	Players["online"] = NumPlayers;
	Players["max"] = MaxPlayers;
	// TODO: Add "sample"

	// Description:
	Json::Value Description;
	Description["text"] = ServerDescription.c_str();

	// Create the response:
	Json::Value ResponseValue;
	ResponseValue["version"] = Version;
	ResponseValue["players"] = Players;
	ResponseValue["description"] = Description;
	m_Client->ForgeAugmentServerListPing(ResponseValue);
	if (!Favicon.empty())
	{
		ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
	}

	// Serialize the response into a packet:
	Json::FastWriter Writer;
	cPacketizer Pkt(*this, 0x00);  // Response packet
	Pkt.WriteString(Writer.write(ResponseValue));
}
Exemplo n.º 10
0
IOTAPI::IOTAPI_err IOT_API::SendData(const std::string& devId, const std::vector<IOT_WriteData>& data) const
{
    IOTAPI::IOTAPI_err ret = IOT_ERR_PARAM;
    Json::Value writeData;

    if(data.empty()) {
        return ret;
    }

    for(uint32_t i = 0; i < data.size(); ++i)
    {
        Json::Value oneData;
        if(data.at(i).ToJSON(oneData)) {
            writeData.append(oneData);
        } else {
            return ret;
        }
    }

    std::string url = m_servAddr + IOT_WRITE_PATH + "/" + devId;
    std::string response;
    Json::FastWriter fastWriter;
    std::string json = fastWriter.write(writeData);

    ret = m_client.PostAndReadResponse(url, m_authName, m_password, json, response);

    Json::Value writeAnswer;
    if(ParseJson(response, writeAnswer)) {
        if(ret != IOTAPI::IOT_ERR_OK) {
            ret = GetErrorCode(writeAnswer);
        } else if(writeAnswer.isMember("totalWritten") && writeAnswer["totalWritten"].isIntegral()) {
            if(writeAnswer["totalWritten"].asUInt() == data.size())
                ret = IOT_ERR_OK;
        } else {
            ret = IOT_ERR_GENERAL;
        }
    }

    return ret;
}
Exemplo n.º 11
0
bool ContextMenuUtil::PerformAction(int command)
{
	ContextMenuItem* contextMenuItem;

	if (!GetContextMenuItem(command, &contextMenuItem))
	{
		return false;
	}

	Json::Value jsonValue;

	jsonValue[NATIVITY_UUID] = StringUtil::toString(contextMenuItem->GetUuid()->c_str());

	for (vector<wstring>::iterator it = _selectedFiles->begin(); it != _selectedFiles->end(); it++)
	{
		wstring selectedFile = *it;

		jsonValue[NATIVITY_FILES].append(StringUtil::toString(selectedFile));
	}

	Json::Value jsonRoot;

	jsonRoot[NATIVITY_COMMAND] = NATIVITY_CONTEXT_MENU_ACTION;
	jsonRoot[NATIVITY_VALUE] = jsonValue;

	Json::FastWriter jsonWriter;

	wstring* jsonMessage = new wstring();

	jsonMessage->append(StringUtil::toWstring(jsonWriter.write(jsonRoot)));

	wstring* response = new wstring();

	if (!_communicationSocket->SendMessageReceiveResponse(jsonMessage->c_str(), response))
	{
		return false;
	}

	return true;
}
std::string ScreenDisplayNDK::sdgetsize() {
	bb::device::DisplayInfo display;
	Json::FastWriter writer;
	Json::Value root;

	double physx = display.physicalSize().width();
	double physy = display.physicalSize().height();
	int pixx = display.pixelSize().width();
	int pixy = display.pixelSize().height();
	double ppmm = 0;
	double ppmmx = 0;
	double ppmmy = 0;
	double pshape = 0;

	double physdiag = 0; // Diagonal metrics
	double pixdiag = 0;

	if((pixx > 0) && (pixy > 0) && (physx > 0) && (physy > 0)) {
		ppmmx = pixx / physx;
		ppmmy = pixy / physy;
		pshape = (ppmmx / ppmmy);
		physdiag = sqrt((physx * physx) + (physy * physy));
		pixdiag = sqrt((pixx * pixx) + (pixy * pixy));
		ppmm = pixdiag / physdiag;
	}

	root["physicalWidth"] = physx;
	root["physicalHeight"] = physy;
	root["pixelWidth"] = pixx;
	root["pixelHeight"] = pixy;
	root["ppmm"] = ppmm;
	root["ppmmX"] = ppmmx;
	root["ppmmY"] = ppmmy;
	root["ppi"] = ppmm * MMPERINCH;
	root["ppiX"] = ppmmx * MMPERINCH;
	root["ppiY"] = ppmmy * MMPERINCH;
	root["pixelShape"] = pshape;

	return writer.write(root);
}
Exemplo n.º 13
0
void cProtocolRecognizer::HandlePacketStatusRequest(void)
{
	cServer * Server = cRoot::Get()->GetServer();
	AString ServerDescription = Server->GetDescription();
	auto NumPlayers = static_cast<signed>(Server->GetNumPlayers());
	auto MaxPlayers = static_cast<signed>(Server->GetMaxPlayers());
	AString Favicon = Server->GetFaviconData();
	cRoot::Get()->GetPluginManager()->CallHookServerPing(*m_Client, ServerDescription, NumPlayers, MaxPlayers, Favicon);

	// Version:
	Json::Value Version;
	Version["name"] = "Cuberite " MCS_CLIENT_VERSIONS;
	Version["protocol"] = MCS_LATEST_PROTOCOL_VERSION;

	// Players:
	Json::Value Players;
	Players["online"] = NumPlayers;
	Players["max"] = MaxPlayers;
	// TODO: Add "sample"

	// Description:
	Json::Value Description;
	Description["text"] = ServerDescription.c_str();

	// Create the response:
	Json::Value ResponseValue;
	ResponseValue["version"] = Version;
	ResponseValue["players"] = Players;
	ResponseValue["description"] = Description;
	if (!Favicon.empty())
	{
		ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
	}

	Json::FastWriter Writer;
	AString Response = Writer.write(ResponseValue);

	cPacketizer Pkt(*this, 0x00);  // Response packet
	Pkt.WriteString(Response);
}
Exemplo n.º 14
0
std::string const* MessageFactory::CreateMoveMessage(enum Tetromino::Move move, int pieceId) const {
    Json::Value root;
    Json::FastWriter writer;

    Json::Value comm_type ("GameMove");
    Json::Value client_token (m_clientToken);

    root["comm_type"] = comm_type;
    root["client_token"] = client_token;
    if (move == Tetromino::left) {
        Json::Value moveV ("left");
        root["move"] = moveV;
    }
    else if (move == Tetromino::right) {
        Json::Value moveV ("right");
        root["move"] = moveV;
    }
    else if (move == Tetromino::down) {
        Json::Value moveV ("down");
        root["move"] = moveV;
    }
    else if (move == Tetromino::lrotate) {
        Json::Value moveV ("lrotate");
        root["move"] = moveV;
    }
    else if (move == Tetromino::rrotate) {
        Json::Value moveV ("rrotate");
        root["move"] = moveV;
    }
    else if (move == Tetromino::drop) {
        Json::Value moveV ("drop");
        root["move"] = moveV;
    }

    Json::Value number (pieceId);
    root["piece_number"] = number;

    std::string const* serialized = new std::string(writer.write(root));
    return serialized;
}
Exemplo n.º 15
0
// register obj
std::string CmdRegister::to_json()
{
    std::string jstr;

    Json::Features::all();
    Json::Value root;
    // Json::StyledWriter jwriter;
    Json::FastWriter fjwriter;

    root["cmd_id"] = cmd_id;
    root["cmd_seq"] = cmd_seq;
    root["display_name"] = display_name;
    root["user_name"] = user_name;
    root["password"] = password;
    root["sip_server"] = sip_server;
    root["acc_id"] = acc_id;
    root["unregister"] = unregister;

    jstr = fjwriter.write(root);

    return jstr;
}
Exemplo n.º 16
0
///////// hangup obj
std::string CmdHangupCall::to_json()
{
    std::string jstr;

    Json::Features::all();
    Json::Value root;
    // Json::StyledWriter jwriter;
    Json::FastWriter jwriter;

    root["cmd_id"] = cmd_id;
    root["cmd_seq"] = cmd_seq;
    root["call_id"] = call_id;
    root["reason_no"] = reason_no;
    root["reason_text"] = reason_text;

    jstr = jwriter.write(root);

    // 中文会出问题啊。

    return jstr;

}
Exemplo n.º 17
0
    void send_request(const Json::Value &request, Json::Value &response) {
        Json::FastWriter writer;
        Json::Reader reader;

        response.clear();

        string request_str = writer.write(request);

        if (m_verbose) {
            cout << "\n" << request_str << "\n";
        }

        string ret = send_msg(request_str);

        if (m_verbose) {
            cout << "\n" << ret << "\n";
        }

        EXPECT_TRUE(reader.parse(ret, response, false));
        EXPECT_EQ(response["jsonrpc"], "2.0");
        EXPECT_EQ(response["id"], request["id"]);
    }
Exemplo n.º 18
0
void CDlgExpEditorDM::OnOK()
{
	// TODO: 在此添加专用代码和/或调用基类
	m_editExp.GetWindowText(m_strExp);
	m_strExp.Replace("\r\n", "");

	Json::Reader Jreader;
	Json::Value Jv;
	Json::FastWriter Jwriter;
	Json::Value JvRet;

	m_Jv["NewExp"] = m_strExp.GetBuffer();

	std::string str = Jwriter.write(m_Jv);

	ProcessUpdate(str.c_str());

	//MessageBox(str.c_str());
	return;

	CBCGPDialog::OnOK();
}
Exemplo n.º 19
0
// 获取待发送的数据,可先获取data长度,如:GetSendData(NULL, 0, dataLen);
bool SendMsgTask::GetSendData(void* data, unsigned int dataSize, unsigned int& dataLen)
{
	bool result = false;
	
	// 构造json协议
	Json::Value root;
	root[TARGETID_PARAM] = m_userId;
	root[MESSAGE_PARAM] = m_message;
	root[ILLEGAL_PARAM] = m_illegal;
	root[TICKET_PARAM] = m_ticket;
	Json::FastWriter writer;
	string json = writer.write(root);

	// 填入buffer
	if (json.length() < dataSize) {
		memcpy(data, json.c_str(), json.length());
		dataLen = json.length();

		result  = true;
	}
	return result;
}
Exemplo n.º 20
0
string CRoute_manager::prepare_infodata()  // 和运维采用json传递数据
{
	vector<ipset_t>::iterator it;
	Json::Value root;
	for( it = _route_table.begin(); it != _route_table.end() ; it++)
	{
		Json::Value set;
		set["IP1"] = Json::Value( ip_num2str((*it).ip1) );
		set["IP2"] = Json::Value( ip_num2str((*it).ip2) );
		set["IP3"] = Json::Value( ip_num2str((*it).ip3) );
		set["lower"] = Json::Value( (*it).lower_bounds );
		set["uppper"] = Json::Value( (*it).upper_bounds );

		root["cell_addr"].append(set);
		
	}

	Json::FastWriter writer;
	string jsonstr = writer.write(root);

	return jsonstr;
}
Exemplo n.º 21
0
  void WorkflowJSON_Impl::parseRunOptions()
  {
    if (m_runOptions){
      disconnectRunOptions();
      m_runOptions.reset();
    }

    if (m_value.isMember("run_options")){
      Json::Value options = m_value["run_options"];

      Json::FastWriter writer;
      std::string s = writer.write(options);

      m_runOptions = RunOptions::fromString(s);
      if (!m_runOptions){
        LOG_AND_THROW("Run options cannot be processed");
      }

      connectRunOptions();
      m_value.removeMember("run_options");
    }
  }
// 获取待发送的数据,可先获取data长度,如:GetSendData(NULL, 0, dataLen);
bool SendMagicIconTask::GetSendData(void* data, unsigned int dataSize, unsigned int& dataLen)
{
	bool result = false;
	
	// 构造json协议
	Json::Value root;
	root[USERID_PARAM] = m_userId;
	root[ICONID_PARAM] = m_iconId;
	root[MSG_PARAM] = m_iconId;
	root[TICKET_PARAM] = m_ticket;
	Json::FastWriter writer;
	string json = writer.write(root);

	// 填入buffer
	if (json.length() < dataSize) {
		memcpy(data, json.c_str(), json.length());
		dataLen = json.length();

		result  = true;
	}
	return result;
}
Exemplo n.º 23
0
bool ChromeProfile::WriteUILocale()
{
	Json::Value root;
	wstring path = m_installLocation + GetUIRelPathAndFile();
	std::ifstream in(path.c_str());
	Json::Reader reader;
	Json::FastWriter writer;
	string langcode;
	bool rslt;
	
	if (in.fail())
	{
		g_log.Log(L"ChromeProfile::WriteUILocale. Cannot open for reading %s", (wchar_t*) path.c_str());
		return false;
	}
	rslt = reader.parse(in, root);
	in.close();

	if (rslt == false)
	{
		g_log.Log(L"ChromeProfile::WriteUILocale. Cannot parse %s", (wchar_t*) path.c_str());
		return false;
	}

	root["intl"]["app_locale"] = CHROMEAPP_LANGUAGECODE_STR;

	std::ofstream out(path.c_str());

	if (out.fail())
	{
		g_log.Log(L"ChromeProfile::WriteUILocale. Cannot open for writing %s", (wchar_t*) path.c_str());
		return false;
	}

	std::string jsonMessage  = writer.write(root);
	out << jsonMessage;
	out.close();
	return true;	
}
Exemplo n.º 24
0
string Triangle::getChunk(){
	Json::FastWriter writer;
	std::string s = writer.write(this->getJson());
	if (!s.empty() && s[s.length()-1] == '\n') {
		s.erase(s.length()-1);
	}
	return s;
	
	/*string chunk = "{";
	chunk.append("\"type\": \"Triangle\",");
		chunk.append("\"bbox\": {");
		chunk.append("\"x1\":");
		chunk.append("\"");
		chunk.append(intToString(this->bbox.x));
		chunk.append("\",");
	
		chunk.append("\"y1\":");
		chunk.append("\"");
		chunk.append(intToString(this->bbox.y));
		chunk.append("\",");
	
		chunk.append("\"x2\":");
		chunk.append("\"");
		chunk.append(intToString(this->bbox.x+this->bbox.width));
		chunk.append("\",");
	
		chunk.append("\"y2\":");
		chunk.append("\"");
		chunk.append(intToString(this->bbox.y+this->bbox.height));
		chunk.append("\"");
		chunk.append("}");
	chunk.append(",");
	chunk.append("\"color\": ");
	chunk.append("\"");
	chunk.append(this->color);
	chunk.append("\"");
	chunk.append("}");
	return 	chunk;*/
}
Exemplo n.º 25
0
string RelicObj::Convert_to_Json(RelicObj obj)
{
	using namespace std;
	
	Json::Value root;
	//set size node////////////////////////////////////////////////////////////////////////
	Json::Value size;
	size["height"] = obj.img_height;
	size["width"] = obj.img_width;
	root["img_size"] = size;
	//set keypoints and descriptors////////////////////////////////////////////////////////////////////////
	Json::Value feature;	
	feature["keypoints"] = Keypoints_to_Json_Obj(this->keypoints);
	feature["descriptors"] = Descriptors_to_Json_Obj(this->descriptors);
	//////////////////////////////////////////////////////////////////////////
	root["feature"] = feature;
	//root.toStyledString();
	//std::string out = root.toStyledString();
	//std::cout << out << std::endl;
	Json::FastWriter writer;
	return writer.write(root);
}
Exemplo n.º 26
0
Options PipelineReaderJSON::extractOptions(Json::Value& node)
{
    Options options;

    for (const std::string& name : node.getMemberNames())
    {
        Json::Value& subnode(node[name]);

        if (name == "plugin")
        {
            PluginManager<Stage>::loadPlugin(subnode.asString());

            // Don't actually put a "plugin" option on
            // any stage
            continue;
        }

        if (extractOption(options, name, subnode))
            continue;
        else if (subnode.isArray())
        {
            for (const Json::Value& val : subnode)
                if (!extractOption(options, name, val))
                    throw pdal_error("JSON pipeline: Invalid value type for "
                        "option list '" + name + "'.");
        }
        else if (subnode.isObject())
        {
            Json::FastWriter w;
            options.add(name, w.write(subnode));
        }
        else
            throw pdal_error("JSON pipeline: Value of stage option '" +
                name + "' cannot be converted.");
    }
    node.clear();
    return options;
}
Exemplo n.º 27
0
void CtrlPoint::OnConnected(const std::string& json, Channel* channel) {

    Json::Value root;
    Json::Reader reader;
    reader.parse(json.c_str(), root);

    const std::string& id = root["id"].asString();
    printf(" id: %s\n device: %s\n nickname: %s\n protocol: %s\n\n"
        , id.c_str()
        , root["device"].asCString()
        , root["nickname"].asCString()
        , root["protocol"].asCString());

    ServiceBroker* s = service_factory_[id];
    // TODO(ghilbut):
    // I'm worryed about channel's life sycle
    {
        // TODO(ghilbut):
        // if service proxy created here bind handlers
        // or, it is not necessary.
        // s->BindCommonPathHandler(boost::bind(&CtrlPoint::handle_get_common_path, this, _1, _2));
        // s->BindDisconnectedHandler(boost::bind(&CtrlPoint::handle_disconnected, this, _1));
    }
    s->BindChannel(channel);

    connecting_list_.insert(id);
    net_manager_.UnregisterSsdpTarget("ethernet", id);

    {
        Json::Value root(Json::objectValue);
        root["event"] = "ServiceAdded";
        root["id"] = id;

        Json::FastWriter writer;
        const std::string json = writer.write(root);
        main_ui_service_.FireEvent(json);
    }
}
Exemplo n.º 28
0
void LikeRoom::OnClose(LikeSessionPtr session, const std::string& name) {
    BOOST_ASSERT_MSG(host_ == session, "[ERROR] host only could close room.\n");
    BOOST_ASSERT_MSG(name_ == name, "[ERROR] local name and event name is not matched.\n");

    Json::Value root(Json::objectValue);
    root["query"] = "close";
    Json::FastWriter writer;
    const std::string json = writer.write(root);

    chat_message msg;
    strcpy(msg.body(), json.c_str());
    msg.body_length(json.length());
    msg.encode_header();

    Guests::iterator itr = guests_.begin();
    Guests::iterator end = guests_.end();
    for (; itr != end; ++itr) {
        LikeSessionPtr& guest = const_cast<LikeSessionPtr&>(*itr);
        guest->Write(msg);
        delegate_.OnLeave(guest);
    }
    delegate_.OnClose(session, name_);
}
Exemplo n.º 29
0
wstring CWaveSession::SerializeRequest(CWaveRequest * lpRequest)
{
	ASSERT(lpRequest != NULL);

	// Prepare the request basics.

	Json::Value vRoot(Json::objectValue);

	vRoot[L"a"] = Json::Value(GetSessionID());
	vRoot[L"r"] = Json::Value(Format(L"%x", m_nNextRequestID++));
	vRoot[L"t"] = Json::Value(lpRequest->GetType());
	vRoot[L"p"] = Json::Value(Json::objectValue);

	// Let the request object write the parameters.

	lpRequest->CreateRequest(vRoot[L"p"]);

	// Get the encoded JSON data.

	Json::FastWriter vWriter;

	return vWriter.write(vRoot);
}
Exemplo n.º 30
0
/**
 * It will be called from JNext JavaScript side with passed string.
 * This method implements the interface for the JavaScript to native binding
 * for invoking native code. This method is triggered when JNext.invoke is
 * called on the JavaScript side with this native objects id.
 */
string GSECryptoJS::InvokeMethod(const string& command) {
	// command appears with parameters following after a space
	size_t commandIndex = command.find_first_of(" ");
	std::string strCommand = command.substr(0, commandIndex);
	size_t callbackIndex = command.find_first_of(" ", commandIndex + 1);
	std::string callbackId = command.substr(commandIndex + 1, callbackIndex - commandIndex - 1);
	std::string arg = command.substr(callbackIndex + 1, command.length());

	if (strCommand == "hash") {
		return gseCryptoController->hash(arg);
	} else if (strCommand == "encrypt") {
		return gseCryptoController->encrypt(arg);
	} else if (strCommand == "decrypt") {
		return gseCryptoController->decrypt(arg);
	} else if (strCommand == "random") {
		return gseCryptoController->random(arg);
	}

	Json::Value error;
	error["error"] = "No implementation found for " + strCommand + "(" + arg + ")";
	Json::FastWriter writer;
	return writer.write(error);
}