Exemplo n.º 1
0
bool MinecraftDynmapProto::doSendMessage(const std::string &message_text)
{
	handleEntry(__FUNCTION__);

	JSONNode json(JSON_NODE);
	json.push_back(JSONNode("name", m_nick.c_str()));
	json.push_back(JSONNode("message", message_text.c_str()));
	std::string data = json.write();

	http::response resp = sendRequest(MINECRAFTDYNMAP_REQUEST_MESSAGE, &data);

	if (resp.code == HTTP_CODE_OK) {
		JSONNode root = JSONNode::parse(resp.data.c_str());
		if (root) {
			const JSONNode &error_ = root["error"];
			if (error_) {
				std::string error = error_.as_string();
				if (error == "none") {
					return handleSuccess(__FUNCTION__);
				}
				else if (error == "not-allowed") {
					UpdateChat(NULL, Translate("Message was not sent. Probably you are sending them too fast or chat is disabled completely."));
				}
			}
		}
	}

	return handleError(__FUNCTION__);
}
Exemplo n.º 2
0
JSONNode ModuleManager::convertIrcChannelToJSONString(IrcChannel& channel) {
	JSONNode n(JSON_NODE);
	n.push_back(JSONNode("name", channel.name));
	n.push_back(JSONNode("topic", channel.topic));

	n.push_back(JSONNode("nameListFull", channel.nameListFull));

	JSONNode n2(JSON_ARRAY);
	n2.set_name("members");
	std::vector<IrcChannelMember>::iterator iter;
	for(iter=channel.members.begin(); iter!=channel.members.end(); ++iter) {
		JSONNode n3(JSON_NODE);
		n3.push_back(JSONNode("nick", (*iter).nick));

		JSONNode n4(JSON_ARRAY);
		n4.set_name("modes");
		for(std::uint64_t i=1; i!=std::uint64_t(1) << 52; i<<=1) {
			bool current_bit = ((*iter).modes & i) != 0;
			n4.push_back(JSONNode("flag", current_bit));
		}
		n3.push_back(n4);

		n2.push_back(n3);
	}
	n.push_back(n2);

	return n;
}
Exemplo n.º 3
0
JSONNode Rig::toJSON() {
  JSONNode root;

  stringstream ss;
  ss << LumiverseCore_VERSION_MAJOR << "." << LumiverseCore_VERSION_MINOR;

  root.push_back(JSONNode("version", ss.str()));
  root.push_back(JSONNode("refreshRate", m_refreshRate));

  JSONNode devices;
  devices.set_name("devices");
  for (auto d : m_devices) {
    devices.push_back(d->toJSON());
  }
  root.push_back(devices);

  JSONNode patches;
  patches.set_name("patches");
  for (auto& p : m_patches) {
    JSONNode patch = p.second->toJSON();
    patch.set_name(p.first);
    patches.push_back(patch);
  }
  root.push_back(patches);

  return root;
}
Exemplo n.º 4
0
JSONNode xmm::TrainingSet::to_json() const
{
    JSONNode json_ts(JSON_NODE);
    json_ts.set_name("TrainingSet");
    
    json_ts.push_back(JSONNode("bimodal", bimodal_));
    json_ts.push_back(JSONNode("dimension", dimension_));
    if (bimodal_)
        json_ts.push_back(JSONNode("dimension_input", dimension_input_));
    json_ts.push_back(vector2json(column_names_, "column_names"));
    json_ts.push_back(JSONNode("size", phrases.size()));
    JSONNode json_deflabel = defaultLabel_.to_json();
    json_deflabel.set_name("defaultlabel");
    json_ts.push_back(json_deflabel);
    
    // Add phrases
    JSONNode json_phrases(JSON_ARRAY);
    for (const_phrase_iterator it = phrases.begin(); it != phrases.end(); ++it)
    {
        JSONNode json_phrase(JSON_NODE);
        json_phrase.push_back(JSONNode("index", it->first));
        json_phrase.push_back(phraseLabels.at(it->first).to_json());
        json_phrase.push_back(it->second->to_json());
        json_phrases.push_back(json_phrase);
    }
    json_phrases.set_name("phrases");
    json_ts.push_back(json_phrases);
    
    return json_ts;
}
Exemplo n.º 5
0
IrcModuleConnection IrcModule::connect(const std::string& id, const std::string& server, const std::string& nick, int port) {
	JSONNode n(JSON_NODE);
	n.push_back(JSONNode("id", id));
	n.push_back(JSONNode("server", server));
	n.push_back(JSONNode("nick", nick));
	n.push_back(JSONNode("port", port));

	IrcConnection* con = (IrcConnection*)ModuleManager_callMethodWithPtrReturn(mModuleManager, mID.c_str(), "IRC", "connect", n.write().c_str(), NULL);
	return IrcModuleConnection(mID, mModuleManager, con);
}
Exemplo n.º 6
0
JSONNode LumiverseFloat::toJSON(string name) {
  JSONNode node;
  node.set_name(name);

  node.push_back(JSONNode("type", getTypeName()));
  node.push_back(JSONNode("val", m_val));
  node.push_back(JSONNode("default", m_default));
  node.push_back(JSONNode("max", m_max));
  node.push_back(JSONNode("min", m_min));

  return node;
}
void JSONResult::setStatus(std::string status, std::string msg){
  if(_statusAllreadySetted){
    throw org::esb::lang::Exception("Status in JSONResult allready setted");
  }
  JSONNode s(JSON_NODE);
  s.set_name("response");
  s.push_back(JSONNode("status",status));
  s.push_back(JSONNode("message",msg));
  s.push_back(JSONNode("requestID",_uuid));
  (*this)["response"].swap(s);
  _statusAllreadySetted=true;
}
JSONResult::JSONResult(org::esb::core::http::HTTPServerRequest&req):_req(req){
  _statusAllreadySetted=false;
  _uuid=_req.get("requestUUID");
  JSONNode s(JSON_NODE);
  s.set_name("response");
  s.push_back(JSONNode("status","ok"));
  s.push_back(JSONNode("message",""));
  s.push_back(JSONNode("requestID",_uuid));
  push_back(s);
  
  _req.response().setContentType("application/javascript; charset=UTF-8");
}
Exemplo n.º 9
0
JSONNode xmm::Label::to_json() const
{
    JSONNode json_label(JSON_NODE);
    json_label.set_name("label");
    if (type == INT) {
        json_label.push_back(JSONNode("type", "INT"));
        json_label.push_back(JSONNode("value", intLabel_));
    } else {
        json_label.push_back(JSONNode("type", "SYM"));
        json_label.push_back(JSONNode("value", symLabel_));
    }
    return json_label;
}
Exemplo n.º 10
0
  /**
   * Helper utility for converting from flexible_type to json.
   * TODO: Fill in details 
   */
  inline JSONNode flexible_type_to_json(const flexible_type& val, std::string name) {

    if (val.get_type() == flex_type_enum::INTEGER) {
      // long cast needed to avoid a ambiguity error which seems to only show up
      // on mac clang++
      if (std::isnan(val.get<flex_int>())) {
        // treat nan as missing value null
        JSONNode v(JSON_NULL);
        v.set_name(name);
        v.nullify();
        return v;
      } else {
        return JSONNode(name, (long)val.get<flex_int>());
      }
    } else if (val.get_type() == flex_type_enum::FLOAT) {
      if (std::isnan(val.get<double>())) {
        // treat nan as missing value null
        JSONNode v(JSON_NULL);
        v.set_name(name);
        v.nullify();
        return v;
      } else {
        return JSONNode(name, val.get<double>());
      }
    } else if (val.get_type() == flex_type_enum::STRING) {
      return JSONNode(name, val.get<flex_string>());
    } else if (val.get_type() == flex_type_enum::VECTOR) {
      const std::vector<double>& v = val.get<flex_vec>();
      JSONNode vec(JSON_ARRAY);
      for (size_t i = 0;i < v.size(); ++i) {
        JSONNode vecval(JSON_NUMBER);
        vecval= v[i];
        vec.push_back(vecval);
      }
      vec.set_name(name);
      return vec;
    } else if (val.get_type() == flex_type_enum::DICT){
      return JSONNode(name, val.get<flex_string>());
    } else if (val.get_type() == flex_type_enum::UNDEFINED){
      JSONNode v(JSON_NULL);
      v.set_name(name);
      v.nullify();
      return v;
    }

    JSONNode v(JSON_NULL);
    v.set_name(name);
    v.nullify();
    return v;
  }
Exemplo n.º 11
0
JSONNode Keyframe::toJSON() {
  JSONNode keyframe;
  keyframe.push_back(JSONNode("t", (unsigned long) t));
  if (val != nullptr) {
    keyframe.push_back(val->toJSON("val"));
  }
  keyframe.push_back(JSONNode("useCurrentState", useCurrentState));

  if (timelineID != "") {
    keyframe.push_back(JSONNode("timelineID", timelineID));
    keyframe.push_back(JSONNode("timelineOffset", (unsigned long)timelineOffset));
  }

  return keyframe;
}
Exemplo n.º 12
0
IrcModuleConnection IrcModule::getConnection(const std::string& id) {
	JSONNode n(JSON_NODE);
	n.push_back(JSONNode("id", id));

	IrcConnection* con = (IrcConnection*)ModuleManager_callMethodWithPtrReturn(mModuleManager, mID.c_str(), "IRC", "getConnection", n.write().c_str(), NULL);
	return IrcModuleConnection(mID, mModuleManager, con);
}
Exemplo n.º 13
0
const JSONNode JSONModelGetter::operator()(uint64_t fn){
    JSONNode::const_iterator it = data->find(num2str(fn));
    if(it!=data->end()) {
        return *it;
    }
    return JSONNode();
}
Exemplo n.º 14
0
Model ASTUtil::get_model(uint64_t fn, ModelGetter *model_getter)
{
    if(model_getter){
        JSONNode n = model_getter->operator()(fn);
        return Model(n);
    }
    return Model(JSONNode());
}
Exemplo n.º 15
0
JSONNode Event::toJSON() {
  // this is equivalent to saying "something happened here but I have no idea what it is"
  JSONNode e;
  e.set_name(_id);
  e.push_back(JSONNode("type", getType()));

  return e;
}
Exemplo n.º 16
0
JSONNode Message::get_batch()
{
    JSONNode::iterator it(msg_.find(fplog::Message::Optional_Fields::batch));

    if (it != msg_.end())
        return *it;

    return JSONNode(JSON_ARRAY);
}
Exemplo n.º 17
0
JSONNode ModuleManager::convertIrcMessageToJSONString(IrcMessage& message) {
	JSONNode n(JSON_NODE);
	n.push_back(JSONNode("ircLine", message.ircLine));
	n.push_back(JSONNode("prefix", message.prefix));
	n.push_back(JSONNode("hasDetailedPrefix", message.hasDetailedPrefix));

	JSONNode n2(JSON_NODE);
	n2.set_name("msgPrefix");
	n2.push_back(JSONNode("nick_or_server", message.msgPrefix.nick_or_server));
	n2.push_back(JSONNode("user", message.msgPrefix.user));
	n2.push_back(JSONNode("host", message.msgPrefix.host));
	n.push_back(n2);

	n.push_back(JSONNode("command", message.command));
	n.push_back(JSONNode("isNumeric", message.isNumeric));
	n.push_back(JSONNode("target", message.target));
	n.push_back(JSONNode("params", message.params));

	return n;
}
Exemplo n.º 18
0
void StreamingDevice::onClientAttach(ClientConn* client){
	Device::onClientAttach(client);
	
	JSONNode n(JSON_NODE);
	n.push_back(JSONNode("_action", "deviceConfig"));

	JSONNode jstate = stateToJSON();
	jstate.set_name("device");
	n.push_back(jstate);
	
	client->sendJSON(n);
}
Exemplo n.º 19
0
bool WSStreamListener::handleNewData(){
	unsigned nchunks = howManySamples();
	if (!nchunks) return true;
	
	JSONNode n(JSON_NODE);

	n.push_back(JSONNode("id", id));
	n.push_back(JSONNode("idx", outIndex));
	
	if (outIndex == 0){
		if (triggerForce && index > triggerForceIndex){
			n.push_back(JSONNode("triggerForced", true));
		}
		if (triggered){
			n.push_back(JSONNode("subsample", triggerSubsampleError));
		}
		n.push_back(JSONNode("sampleIndex", index));
	}
	
	JSONNode streams_data(JSON_ARRAY);
	streams_data.set_name("data");
	
	BOOST_FOREACH(Stream* stream, streams){
		JSONNode a(JSON_ARRAY);
		
		for (unsigned chunk = 0; chunk < nchunks; chunk++){
			a.push_back(JSONNode("", 
				device->resample(*stream, index+chunk*decimateFactor, decimateFactor)
			));
		}
		
		streams_data.push_back(a);
	}
Exemplo n.º 20
0
MEVENT CSkypeProto::AppendDBEvent(MCONTACT hContact, MEVENT hEvent, const char *szContent, const char *szUid, time_t edit_time)
{
	mir_cslock lck(m_AppendMessageLock);
	DBEVENTINFO dbei = { sizeof(dbei) };
	dbei.cbBlob = db_event_getBlobSize(hEvent);
	dbei.pBlob = mir_ptr<BYTE>((PBYTE)mir_alloc(dbei.cbBlob));
	db_event_get(hEvent, &dbei);

	JSONNode jMsg = JSONNode::parse((char*)dbei.pBlob);
	if (jMsg)
	{
		JSONNode &jEdits = jMsg["edits"];
		if (jEdits)
		{
			for (auto it = jEdits.begin(); it != jEdits.end(); ++it)
			{
				const JSONNode &jEdit = *it;

				if (jEdit["time"].as_int() == edit_time)
					return hEvent;
			}
			JSONNode jEdit;
			jEdit 
				<< JSONNode("time", (long)edit_time)
				<< JSONNode("text", szContent);

			jEdits << jEdit;
		}
	}
	else
	{
		jMsg = JSONNode();
		JSONNode jOriginalMsg; jOriginalMsg.set_name("original_message");
		JSONNode jEdits(JSON_ARRAY); jEdits.set_name("edits");
		JSONNode jEdit;

		jOriginalMsg
			<< JSONNode("time", (long)dbei.timestamp)
			<< JSONNode("text", (char*)dbei.pBlob);

		jMsg << jOriginalMsg;

		jEdit 
			<< JSONNode("time", (long)edit_time)
			<< JSONNode("text", szContent);

		jEdits << jEdit;	
		jMsg   << jEdits;


	}
	db_event_delete(hContact, hEvent);	
	return AddDbEvent(SKYPE_DB_EVENT_TYPE_EDITED_MESSAGE, hContact, dbei.timestamp, DBEF_UTF, jMsg.write().c_str(), szUid);
}
Exemplo n.º 21
0
ToxHexAddress ResolveToxAddressFromToxme(HANDLE hNetlib, const char *query)
{
    ToxHexAddress address = ToxHexAddress::Empty();

    HttpRequest request(REQUEST_POST, "https://toxme.io/api");
    JSONNode root(JSON_NODE);
    root
            << JSONNode("action", 3)
            << JSONNode("name", query);
    json_string data = root.write();
    request.SetData(data.c_str(), data.length());

    NLHR_PTR response(request.Send(hNetlib));
    if (response->resultCode != HTTP_CODE_OK || !response->pData)
        return ToxHexAddress::Empty();

    root = JSONNode::parse(response->pData);
    if (root.empty())
        return ToxHexAddress::Empty();

    json_string id = root.at("tox_id").as_string();
    return ToxHexAddress(id.c_str());
}
void
ProgrammableOpAttributes::LoadRKernel(const std::string& name, const JSONNode &atts, const std::string& code)
{
    script = JSONNode();
    scriptMap = "";

    stringVector args;
    SetupPipeline(atts,args,name);

    JSONNode vars = JSONNode::JSONArray();
    for(int i = 0; i < args.size(); ++i)
        vars.Append(args[i]);

    JSONNode node;
    node["vars"] = vars;

    std::string argstring = "";
    for(size_t i = 0; i < args.size(); ++i)
        argstring += args[i] + (i == args.size()-1 ? "" : ",");

    std::ostringstream rwrapper;

    rwrapper << "import rpy2,numpy\n"
             << "import rpy2.robjects as robjects\n"
             << "import rpy2.robjects.numpy2ri\n"
             << "rpy2.robjects.numpy2ri.activate()\n"
             << name << " = robjects.r('''\n"
             << code << "\n"
             << "''')\n"
             << "setout(numpy.asarray(" << name << "(" << argstring << ")))\n";

    std::string escapedCode = rwrapper.str();
    //std::cout << escapedCode << std::endl;
    replace(escapedCode, "\n", "\\n");

    node["source"] = escapedCode;

    script["scripts"][name] = node;

    //update scriptmap
    scriptMap = script.ToString();

    AddNode(name,name);
    AddFinalOutputConnection(name);

}
Exemplo n.º 23
0
bool Rig::load(string filename) {
  stop();

  // Check to see if we can load the file.
  ifstream data;
  data.open(filename, ios::in | ios::binary | ios::ate);

  if (data.is_open()) {
    reset();

    // "+ 1" for the ending
    streamoff size = data.tellg();
    char* memblock = new char[(unsigned int)size + 1];

    data.seekg(0, ios::beg);

    stringstream ss;
    ss << "Loading " << size << " bytes from " << filename;
    Logger::log(INFO, ss.str());

    data.read(memblock, size);
    data.close();

    // It's not guaranteed that the following memory after memblock is blank.
    // C-style string needs an end.
    memblock[size] = '\0';
      
    JSONNode n = libjson::parse(memblock);

	// Pass in json path with the original json nodes.
	n.push_back(JSONNode("jsonPath", filename));

    // This could get to be a large function, so let's break off into a helper.
    loadJSON(n);

    delete memblock;
    return true;
  }
  else {
    stringstream ss;
    ss << "Error opening " << filename;
    Logger::log(ERR, ss.str());

    return false;
  }
}
void
ProgrammableOpAttributes::LoadPythonKernel(const std::string& name, const JSONNode& atts, const std::string& code)
{
    script = JSONNode();
    scriptMap = "";

    stringVector args;
    SetupPipeline(atts,args,name);

    std::string arglist = "";

    JSONNode vars = JSONNode::JSONArray();

    for(int i = 0; i < args.size(); ++i)
    {
        vars.Append(args[i]);
        arglist += args[i] + (i == args.size()-1 ? "" : ",");
    }

    JSONNode node;
    node["vars"] = vars;

    std::ostringstream pwrapper;

    pwrapper << "from visit_internal_funcs import *\n"
             //<< "exec('''" << "\n"
             //<< code << "''',globals())\n"
             << code << "\n"
             << "setout(" << name << "(" << arglist << "))\n";

    std::string escapedCode = pwrapper.str();
    //std::cout << escapedCode << std::endl;
    //replace(escapedCode, "'", "\"");
    //replace(escapedCode, "\"", "\\\"");
    //replace(escapedCode, "\n", "\\n");

    node["source"] = escapedCode;

    script["scripts"][name] = node;
    scriptMap = script.ToString();

    AddNode(name,name);
    AddFinalOutputConnection(name);
}
Exemplo n.º 25
0
JSONNode *Database::CreateTable(const string &name, const vector<string> &columnNames)
{
	if (this->FindTable(name))
		return NULL;
	JSONNode table;
	table.set_name(name);
	JSONNode columns(JSON_ARRAY);
	columns.set_name("columns");
	for (auto i = columnNames.begin(); i != columnNames.end(); i++)
		columns.push_back(JSONNode("", *i));
	table.push_back(columns);
	JSONNode rows(JSON_ARRAY);
	rows.set_name("rows");
	table.push_back(rows);
	auto tables = data.find("tables");
	tables->push_back(table);
	//cout << tables->write_formatted() << endl;
	//cout << data.write_formatted() << endl;
	auto t = tables->find(name);
	return t == tables->end() ? NULL : &*t;
}
void test_profile_update(){
  HTTPClientSession s(HOST, PORT);
  HTTPRequest request(HTTPRequest::HTTP_PUT, std::string("/api/v1/profile/").append(created_profile_uuid));
  JSONNode base(JSON_NODE);
  base.push_back(JSONNode("name","test profile"));
  base.push_back(JSONNode("description","test description"));

  JSONNode format(JSON_NODE);
  format.set_name("format");
  format.push_back(JSONNode("id","matroska"));
  base.push_back(format);

  
  JSONNode video(JSON_NODE);
  video.set_name("video");
  video.push_back(JSONNode("id","mpeg4"));

  base.push_back(video);
  
  JSONNode audio(JSON_NODE);
  audio.set_name("audio");
  audio.push_back(JSONNode("id","mp2"));
  audio.push_back(JSONNode("ar","44100"));
  audio.push_back(JSONNode("ac","2"));

  base.push_back(audio);

  //request.write(os);
  std::ostream & os=s.sendRequest(request);
  os << base.write_formatted();
  HTTPResponse response;
  std::istream& rs = s.receiveResponse(response);


  std::string data;
  StreamCopier::copyToString(rs, data);
  LOGDEBUG("response:"<<data);
  JSONNode node = getJson(data);
  assert_response(node);
  assert(node.contains("uuid"));
  assert(node["uuid"]==created_profile_uuid);
}
Exemplo n.º 27
0
Message& Message::add_binary(const char* param_name, const void* buf, size_t buf_size_bytes)
{
    if (!param_name || !buf || !buf_size_bytes)
        return *this;

    JSONNode blob(JSON_NODE);
    blob.set_name(param_name);

    size_t dest_len = generic_util::base64_encoded_length(buf_size_bytes);
    char* base64 = new char [dest_len + 1];
    memset(base64, 0, dest_len + 1);
    generic_util::base64_encode(buf, buf_size_bytes, base64, dest_len);

    blob.push_back(JSONNode("blob", base64));

    delete [] base64;

    validate_params_ = false;
            
    try
    {
        add(blob);
    }
    catch(std::exception& e)
    {
        validate_params_ = true;
        throw e;
    }
    catch(fplog::exceptions::Generic_Exception& e)
    {
        validate_params_ = true;
        throw e;
    }

    validate_params_ = true;

    return *this;
}
Notification ActionUpdateClient::toDo() {

    pid_t child_pid;

    child_pid = fork();

    if (child_pid < 0) {
        cout << getpid() << " > Fork failed!!" << endl;
        abort();
    }

    if (child_pid == 0) {

        cout << getpid() << " > Me voy a actualizar!!" << endl;

        /*
         * Esperamos 5 segundos simulando un trabajo
         */

        sleep(10);

        cout << getpid() << " > Termino la actualizacion, creo una conneccion y envio el resultado" << endl;

        ConnectionSSL connection;
        connection.setClient(this->connection->getClient());
        connection.createEncryptedSocket();

        Notification persistent_sender;

        persistent_sender.setAction(ACTION_PERSISTENT_SENDER);
        persistent_sender.addDataItem(JSONNode("Token", ACCESS_TOKEN));

        OutcomingActionExecutor outcoming_executor(&connection);

        outcoming_executor.writeAndWaitResponse(persistent_sender);

        /*
         * Envio los resultados obtenidos
         */

        Notification response;
        response.setAction(ACTION_NOTIFICATION_RESPONSE);
        response.setParentId(this->notification.getId());
        response.clearData();
        response.addDataItem(JSONNode("UpdateStatus", "OK"));

        outcoming_executor.writeAndWaitResponse(response);


        /*
         * Cierro la coneccion
         */

        connection.informClosingToServer();

        connection.manageCloseConnection(0);

    }

    Notification response;
    response.setAction(ACTION_NOTIFICATION_RESPONSE);
    response.setParentId(this->notification.getId());
    response.clearData();
    response.addDataItem(JSONNode("UpdateStatus", "INICIADO"));

    return response;
    
}
void test_profile_create(){
  HTTPClientSession s(HOST, PORT);
  HTTPRequest request(HTTPRequest::HTTP_POST, "/api/v1/profile/");
  //std::ostringstream os;

  
  JSONNode base(JSON_NODE);
  base.push_back(JSONNode("name","test profile"));
  base.push_back(JSONNode("description","test description"));

  JSONNode format(JSON_NODE);
  format.set_name("format");
  format.push_back(JSONNode("id","mp4"));
  base.push_back(format);

  
  JSONNode video(JSON_NODE);
  video.set_name("video");
  //video.push_back(JSONNode("id","mpeg4"));
  video.push_back(JSONNode("id","libx264"));
  video.push_back(JSONNode("qscale","4"));
  video.push_back(JSONNode("aubq","8"));
  video.push_back(JSONNode("me_range","16"));
  video.push_back(JSONNode("qmin","4"));
  video.push_back(JSONNode("qmax","51"));
  video.push_back(JSONNode("qcomp","0.6"));
  video.push_back(JSONNode("qdiff","4"));

  base.push_back(video);
  
  JSONNode audio(JSON_NODE);
  audio.set_name("audio");
  audio.push_back(JSONNode("id","mp2"));
  audio.push_back(JSONNode("ar","44100"));
  audio.push_back(JSONNode("ac","2"));

  base.push_back(audio);

  //request.write(os);
  std::ostream & os=s.sendRequest(request);
  os << base.write_formatted();
  HTTPResponse response;
  std::istream& rs = s.receiveResponse(response);


  std::string data;
  StreamCopier::copyToString(rs, data);
  LOGDEBUG("response:"<<data);
  JSONNode node = getJson(data);
  assert_response(node);
  assert(node.contains("uuid"));
  created_profile_uuid=node["uuid"].as_string();
}
Exemplo n.º 30
0
void TestSuite::TestInspectors(void){
    UnitTest::SetPrefix("TestInspectors.cpp - Inspectors");
    JSONNode test = JSONNode(JSON_NULL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT(""));
	   assertEquals(test.as_int(), 0);
	   assertEquals(test.as_float(), 0.0f);
	   assertEquals(test.as_bool(), false);
    #endif

    test = 15.5f;
    assertEquals(test.type(), JSON_NUMBER);
  #ifdef JSON_CASTABLE
    assertEquals(test.as_string(), JSON_TEXT("15.5"));
  #endif
    assertEquals(test.as_int(), 15);
    assertEquals(test.as_float(), 15.5f);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_bool(), true);
    #endif

    test = 0.0f;
    assertEquals(test.type(), JSON_NUMBER);
  #ifdef JSON_CASTABLE
    assertEquals(test.as_string(), JSON_TEXT("0"));
  #endif
    assertEquals(test.as_int(), 0);
    assertEquals(test.as_float(), 0.0f);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_bool(), false);
    #endif

    test = true;
    assertEquals(test.type(), JSON_BOOL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT("true"));
	   assertEquals(test.as_int(), 1);
	   assertEquals(test.as_float(), 1.0f);
    #endif
    assertEquals(test.as_bool(), true);

    test = false;
    assertEquals(test.type(), JSON_BOOL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT("false"));
	   assertEquals(test.as_int(), 0);
	   assertEquals(test.as_float(), 0.0f);
    #endif
    assertEquals(test.as_bool(), false);

    #ifdef JSON_CASTABLE
	   test.cast(JSON_NODE);
    #else
	   test = JSONNode(JSON_NODE);
    #endif
    assertEquals(test.type(), JSON_NODE);
    assertEquals(test.size(), 0);
    test.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
    test.push_back(JSONNode(JSON_TEXT("hello"), JSON_TEXT("mars")));
    test.push_back(JSONNode(JSON_TEXT("salut"), JSON_TEXT("france")));
    assertEquals(test.size(), 3);
    TestSuite::testParsingItself(test);

    #ifdef JSON_CASTABLE
	   JSONNode casted = test.as_array();
	   #ifdef JSON_UNIT_TEST
		  assertNotEquals(casted.internal, test.internal);
	   #endif
	   assertEquals(casted.type(), JSON_ARRAY);
	   assertEquals(test.type(), JSON_NODE);
	   assertEquals(test.size(), 3);
	   assertEquals(casted.size(), 3);
	   TestSuite::testParsingItself(casted);
    #endif

    UnitTest::SetPrefix("TestInspectors.cpp - Location");

    try {
	   #ifdef JSON_CASTABLE
		  assertEquals(casted.at(0), JSON_TEXT("world"));
		  assertEquals(casted.at(1), JSON_TEXT("mars"));
		  assertEquals(casted.at(2), JSON_TEXT("france"));
		  assertEquals(casted.at(0).name(), JSON_TEXT(""));
		  assertEquals(casted.at(1).name(), JSON_TEXT(""));
		  assertEquals(casted.at(2).name(), JSON_TEXT(""));
	   #endif
	   assertEquals(test.at(0), JSON_TEXT("world"));
	   assertEquals(test.at(1), JSON_TEXT("mars"));
	   assertEquals(test.at(2), JSON_TEXT("france"));
	   assertEquals(test.at(0).name(), JSON_TEXT("hi"));
	   assertEquals(test.at(1).name(), JSON_TEXT("hello"));
	   assertEquals(test.at(2).name(), JSON_TEXT("salut"));
    } catch (std::out_of_range){
	   FAIL("exception caught");
    }

    try {
	   assertEquals(test.at(JSON_TEXT("hi")), JSON_TEXT("world"));
	   assertEquals(test.at(JSON_TEXT("hello")), JSON_TEXT("mars"));
	   assertEquals(test.at(JSON_TEXT("salut")), JSON_TEXT("france"));
	   #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
		  assertEquals(test.at_nocase(JSON_TEXT("SALUT")), JSON_TEXT("france"));
		  assertEquals(test.at_nocase(JSON_TEXT("HELLO")), JSON_TEXT("mars"));
		  assertEquals(test.at_nocase(JSON_TEXT("HI")), JSON_TEXT("world"));
	   #endif
    } catch (std::out_of_range){
	   FAIL("exception caught");
    }

    assertException(test.at(JSON_TEXT("meh")), std::out_of_range);
    #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
	   assertException(test.at_nocase(JSON_TEXT("meh")), std::out_of_range);
    #endif

    assertEquals(test[JSON_TEXT("hi")], json_string(JSON_TEXT("world")));
    assertEquals(test[JSON_TEXT("hello")], json_string(JSON_TEXT("mars")));
    assertEquals(test[JSON_TEXT("salut")], json_string(JSON_TEXT("france")));
    assertEquals(test[0], JSON_TEXT("world"));
    assertEquals(test[1], JSON_TEXT("mars"));
    assertEquals(test[2], JSON_TEXT("france"));

    #ifdef JSON_ITERATORS
	  #ifdef JSON_CASTABLE
	   UnitTest::SetPrefix("TestInspectors.cpp - Iterators");
	   for(JSONNode::iterator it = casted.begin(), end = casted.end(); it != end; ++it){
		  assertEquals((*it).name(), JSON_TEXT(""));
	   }
	  #endif
    #endif

    #ifdef JSON_BINARY
	   UnitTest::SetPrefix("TestInspectors.cpp - Binary");
	   test.set_binary((const unsigned char *)"Hello World", 11);
	   assertEquals(test.type(), JSON_STRING);
	   assertEquals(test.as_string(), JSON_TEXT("SGVsbG8gV29ybGQ="));
	   assertEquals(test.as_binary(), "Hello World");
	   assertEquals(test.as_binary().size(), 11);

	   test = JSON_TEXT("Hello World");
	   assertEquals(test.type(), JSON_STRING);
	   assertEquals(test.as_string(), JSON_TEXT("Hello World"));
	   #ifdef JSON_SAFE
		  assertEquals(test.as_binary(), "");
	   #endif
    #endif

   #ifdef JSON_READ_PRIORITY
	  //This is a regression test for a bug in at()
	  json_string buffer(JSON_TEXT("{ \"myValue1\" : \"foo\", \"myValue2\" : \"bar\"}"));
	  JSONNode current = libjson::parse(buffer);
	  try {
		  JSONNode & value1 = current[JSON_TEXT("myValue1")];
		  assertEquals(value1.as_string(), JSON_TEXT("foo"));
		  JSONNode & value2 = current[JSON_TEXT("myValue2")];
		  assertEquals(value2.as_string(), JSON_TEXT("bar"));
	  } catch (...){
		  assertTrue(false);
	  }
  #endif
}