Exemplo n.º 1
0
// Login subscriber
bool filmonAPIlogin(std::string username, std::string password) {

	bool res = filmonAPIgetSessionKey();
	if (res) {
		XBMC->Log(LOG_DEBUG, "logging in user");
		filmonUsername = username;
		filmonpassword = password;

		std::string md5pwd = PVRXBMC::XBMC_MD5::GetMD5(password);
		std::transform(md5pwd.begin(), md5pwd.end(), md5pwd.begin(), ::tolower);

		std::string params = "login="******"&password="******"tv/api/login", sessionKeyParam + "&" + params, 1);
		if (res) {
			Json::Value root;
			Json::Reader reader;
			reader.parse(response, root);
			// Favorite channels
			channelList.clear();
			Json::Value favouriteChannels = root["favorite-channels"];
			unsigned int channelCount = favouriteChannels.size();
			for (unsigned int channel = 0; channel < channelCount; channel++) {
				Json::Value chId = favouriteChannels[channel]["channel"]["id"];
				channelList.push_back(chId.asUInt());
				XBMC->Log(LOG_INFO, "added channel %u",
					chId.asUInt());
			}
			clearResponse();
		}
	}
	return res;
}
Exemplo n.º 2
0
		void deltaTimeInfo::setDelta(const Json::Value& params)
		{
			uint32_t samples = 1;
			uint32_t seconds = 0;
			uint32_t fraction = 0;
			uint32_t subFraction = 0;

			Json::Value value;

			value = params["samples"];
			if(value.isNull()==false) {
				samples = value.asUInt();
				if(samples==0) {
					throw std::runtime_error("samples must be > 0");
				}
			}

			const Json::Value& timeObject = params["delta"];
			if(timeObject["type"]=="ntp") {
				value = timeObject["seconds"];
				if(value.isNull()==false) {
					seconds = value.asUInt();
				}

				value = timeObject["fraction"];
				if(value.isNull()==false) {
					fraction = value.asUInt();
				}

				value = timeObject["subFraction"];
				if(value.isNull()==false) {
					subFraction = value.asUInt();
				}
			}
			uint64_t ntpTimestamp = seconds;
			ntpTimestamp <<= 32;
			ntpTimestamp |= fraction;



			// we are loosing precision here. In order to compensate this, we calculate a correction to use.
			m_deltaNtpTimestamp = ntpTimestamp/samples;
			m_deltaSubFraction = subFraction/samples;

			// determine remainder and calculate sub fraction from it.
			uint64_t rest = m_deltaNtpTimestamp%samples;
			rest <<= 32;
			rest /= samples;
			m_deltaSubFraction += static_cast < uint32_t > (rest & 0xffffffff);

			std::cout << __FUNCTION__ << std::endl;
			std::cout << "seconds = " << seconds << std::hex << " (0x" << seconds << ")" << std::endl;
			std::cout << "fraction = " << fraction << std::hex << " (0x" << fraction << ")" << std::endl;
			std::cout << "subFraction = " << subFraction << std::hex << " (0x" << subFraction << ")" << std::endl;
		}
Exemplo n.º 3
0
void Attachment::AssignKeyValue(const std::string &key, const Json::Value &val) {
    if(key == std::string("content_type")) {
        content_type = val.asString();
        return;
    }
    if(key == std::string("category")) {
        category = val.asString();
        return;
    }
    if(key == std::string("name")) {
        name = val.asString();
        return;
    }
    if(key == std::string("size")) {
        size = val.asUInt();
        return;
    }
    if(key == "hash") {
        hash = val.asString();
        return;
    }
    if(key == "digest") {
        digest = val.asString();
        return;
    }
}
 bool JsonHelper::ToBool( const Json::Value& value, bool defaultResult )
 {
     if ( value.isBool() )
     {
         return value.asBool();
     }
     if ( value.isInt() )
     {
         return (bool)value.asInt();
     }
     if ( value.isDouble() )
     {
         return (bool)value.asDouble();
     }
     if ( value.isUInt() )
     {
         return (bool)value.asUInt();
     }
     if ( value.isString() )
     {
         const std::string& str = value.asString();
         return ( str == "true" || str == "1" );
     }
     return defaultResult;
 }
Exemplo n.º 5
0
FB::variant jsonValueToVariant( Json::Value root )
{
    Json::Value def;
    if (root.isString())
        return root.asString();
    else if (root.isBool())
        return root.asBool();
    else if (root.isDouble())
        return root.asDouble();
    else if (root.isInt())
        return root.asInt();
    else if (root.isUInt())
        return root.asUInt();
    else if (root.isNull())
        return FB::FBNull();
    else if (root.isArray()) {
        FB::VariantList outList;
        for (size_t i = 0; i < root.size(); ++i) {
            outList.push_back(jsonValueToVariant(root.get(i, def)));
        }
        return outList;
    } else if (root.isObject()) {
        Json::Value::Members members = root.getMemberNames();
        FB::VariantMap outMap;
        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
        {
            outMap[*it] = jsonValueToVariant(root.get(*it, def));
        }
        return outMap;
    } else {
        return FB::FBVoid();
    }
}
Exemplo n.º 6
0
void Object::set (std::string const& k, Json::Value const& v)
{
    auto t = v.type();
    switch (t)
    {
    case Json::nullValue:
        return set (k, nullptr);
    case Json::intValue:
        return set (k, v.asInt());
    case Json::uintValue:
        return set (k, v.asUInt());
    case Json::realValue:
        return set (k, v.asDouble());
    case Json::stringValue:
        return set (k, v.asString());
    case Json::booleanValue:
        return set (k, v.asBool());

    case Json::objectValue:
    {
        auto object = setObject (k);
        copyFrom (object, v);
        return;
    }

    case Json::arrayValue:
    {
        auto array = setArray (k);
        for (auto& item: v)
            array.append (item);
        return;
    }
    }
    assert (false);  // Can't get here.
}
Exemplo n.º 7
0
void _PlanOperation::addField(const Json::Value &field) {
  if (field.isNumeric()) {
    addField(field.asUInt());
  } else if (field.isString()) {
    addNamedField(field.asString());
  } else throw std::runtime_error("Can't parse field name, neither numeric nor std::string");
}
Exemplo n.º 8
0
/// 从 Json 解析数据到 dictNode 中
static void parseFromJsonToDictionary(const Json::Value & jsonNode, CCDictionary * dictNode)
{
	Json::Value::Members members = jsonNode.getMemberNames();
	for (Json::Value::Members::iterator beg = members.begin(); beg != members.end(); ++beg)
	{
        std::string name = *beg;
		Json::Value child = jsonNode[name];
		
		if (child.isArray())
		{
			CCArray * arr = CCArray::create();
			parseFromJsonToArray(child, arr);
			dictNode->setObject(arr, name);
		}
		else if (child.isObject())
		{
			CCDictionary * dict = CCDictionary::create();
			parseFromJsonToDictionary(child, dict);
			dictNode->setObject(dict, name);
		}
		else if (child.isString())
		{
			CCString * str = CCString::createWithFormat("%s", child.asCString());
			dictNode->setObject(str, name);
		}
		else if (child.isInt())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
		else if (child.isUInt())
		{
			CCString * str = CCString::createWithFormat("%u", child.asUInt());
			dictNode->setObject(str, name);
		}
		else if (child.isInt64())
		{
			CCString * str = CCString::createWithFormat("%lld", child.asInt64());
			dictNode->setObject(str, name);
			
		}
		else if (child.isUInt64())
		{
			CCString * str = CCString::createWithFormat("%llu", child.asUInt64());
			dictNode->setObject(str, name);
		}
		else if (child.isDouble())
		{
			CCString * str = CCString::createWithFormat("%f", child.asDouble());
			dictNode->setObject(str, name);
		}
		else if (child.isBool())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
	}
}
Exemplo n.º 9
0
void JsonTree::init( const string &key, const Json::Value &value, bool setType, NodeType nodeType, ValueType valueType )
{
    mKey = key;
	mNodeType = nodeType;
	mParent = 0;
	mValue = "";
	mValueType = valueType;

	if( ! value.isNull() && ( value.isArray() || value.isObject() ) ) {
        if( value.isArray() ) {
            mNodeType = NODE_ARRAY;
            for ( uint32_t i = 0; i < value.size(); i++ ) {
                pushBack( JsonTree( "", value[ i ] ) );
            }
        }
		else if( value.isObject() ) {
            mNodeType = NODE_OBJECT;
            Json::Value::Members members = value.getMemberNames();
            for( Json::Value::Members::const_iterator memberIt = members.begin(); memberIt != members.end(); ++memberIt ) {
				string key = *memberIt;
                pushBack( JsonTree( key, value[ key ] ) );
            }
        }
    }
	else {
		if( value.isBool() ) {
			mValue = toString( value.asBool() );
			if( setType ) {
				mValueType = VALUE_BOOL;
			}
		}
		else if ( value.isDouble() ) { 
			mValue = toString( value.asDouble() );
			if ( setType ) {
				mValueType = VALUE_DOUBLE;
			}
		}
		else if ( value.isInt() ) { 
			mValue = toString( value.asInt() );
			if ( setType ) {
				mValueType = VALUE_INT;
			}
		}
		else if ( value.isString() ) { 
			mValue = toString( value.asString() );
			if ( setType ) {
				mValueType = VALUE_STRING;
			}
		}
		else if ( value.isUInt() ) { 
			mValue = toString( value.asUInt() );
			if ( setType ) {
				mValueType = VALUE_UINT;
			}
		}
	}
}
Exemplo n.º 10
0
bool GetUInt32(const Json::Value& value, uint32_t* out) {
  if (value.isNull()) {
    return false;
  }
  if (!(value.isInt() || value.isUInt())) {
    return false;
  }
  *out = value.asUInt();
  return true;
}
Exemplo n.º 11
0
	void Deserialize_UInt32( const Json::Value& srcValue, UINT32 &dstValue )
	{
		//HACK: Json Cpp saves small unsigned integers as signed ints
		if( srcValue.isInt() )
		{
			const Json::Int signedIntValue = srcValue.asInt();

			if( signedIntValue >= Json::Value::minInt
				&& signedIntValue <= Json::Value::maxInt )
			{
				dstValue = signedIntValue;
				return;
			}
		}

		CHK_VRET_IF_NOT( srcValue.isUInt() );
		Assert( srcValue.asUInt() < MAX_UINT32 );
		dstValue = srcValue.asUInt();
	}
Exemplo n.º 12
0
Arquivo: main.cpp Projeto: tuita/DOMQ
static void
printValueTree( FILE *fout, Json::Value &value, const std::string &path = "." )
{
   switch ( value.type() )
   {
   case Json::nullValue:
      fprintf( fout, "%s=null\n", path.c_str() );
      break;
   case Json::intValue:
      fprintf( fout, "%s=%ld\n", path.c_str(), value.asInt() );
      break;
   case Json::uintValue:
      fprintf( fout, "%s=%lu\n", path.c_str(), value.asUInt() );
      break;
   case Json::realValue:
      fprintf( fout, "%s=%.16g\n", path.c_str(), value.asDouble() );
      break;
   case Json::stringValue:
      fprintf( fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str() );
      break;
   case Json::booleanValue:
      fprintf( fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false" );
      break;
   case Json::arrayValue:
      {
         fprintf( fout, "%s=[]\n", path.c_str() );
         int size = value.size();
         for ( int index =0; index < size; ++index )
         {
            static char buffer[16];
            sprintf( buffer, "[%d]", index );
            printValueTree( fout, value[index], path + buffer );
         }
      }
      break;
   case Json::objectValue:
      {
         fprintf( fout, "%s={}\n", path.c_str() );
         Json::Value::Members members( value.getMemberNames() );
         std::sort( members.begin(), members.end() );
         std::string suffix = *(path.end()-1) == '.' ? "" : ".";
         for ( Json::Value::Members::iterator it = members.begin(); 
               it != members.end(); 
               ++it )
         {
            const std::string &name = *it;
            printValueTree( fout, value[name], path + suffix + name );
         }
      }
      break;
   default:
      break;
   }
}
Exemplo n.º 13
0
k8s_container::list k8s_component::extract_pod_containers(const Json::Value& item)
{
	k8s_container::list ext_containers;
	Json::Value spec = item["spec"];
	if(!spec.isNull())
	{
		Json::Value containers = spec["containers"];
		if(!containers.isNull())
		{
			for (auto& container : containers)
			{
				std::string cont_name;
				Json::Value name = container["name"];
				if(!name.isNull()) { cont_name = name.asString(); }
				else { return ext_containers; }

				k8s_container::port_list cont_ports;
				Json::Value ports = container["ports"];
				for(const auto& port : ports)
				{
					k8s_container::port cont_port;
					Json::Value name = port["name"];
					if(!name.isNull())
					{
						cont_port.set_name(name.asString());
					}
					Json::Value cport = port["containerPort"];
					if(!cport.isNull())
					{
						cont_port.set_port(cport.asUInt());
					}
					else
					{
						g_logger.log("Port not found, setting value to 0", sinsp_logger::SEV_WARNING);
						cont_port.set_port(0);
					}
					Json::Value protocol = port["protocol"];
					if(!protocol.isNull())
					{
						cont_port.set_protocol(protocol.asString());
					}
					else
					{
						std::string port_name = name.isNull() ? "[NO NAME]" : name.asString();
						g_logger.log("Protocol not found for port: " + port_name, sinsp_logger::SEV_WARNING);
					}
					cont_ports.push_back(cont_port);
				}
				ext_containers.emplace_back(k8s_container(cont_name, cont_ports));
			}
		}
	}
	return ext_containers;
}
Exemplo n.º 14
0
 bool Deserialize ( const Json::Value& json_val, unsigned int& obj_val )
 {
     /**
      * Warning: the default type may be int, even you Serialize a uint value
      */
     if ( json_val.isIntegral () )
     {
         obj_val = json_val.asUInt ();
         return true;
     }
     return false;
 }
Exemplo n.º 15
0
// Login subscriber
bool filmonAPIlogin(std::string username, std::string password) {

	bool res = filmonAPIgetSessionKey();
	if (res) {
		std::cerr << "FilmonAPI: logging in user" << std::endl;
		filmonUsername = username;
		filmonpassword = password;
		// Password is MD5 hex
		CryptoPP::Weak1::MD5 hash;
		byte digest[CryptoPP::Weak1::MD5::DIGESTSIZE];
		hash.CalculateDigest(digest, (byte*) password.c_str(),
				password.length());
		CryptoPP::HexEncoder encoder;
		std::string md5pwd;
		encoder.Attach(new CryptoPP::StringSink(md5pwd));
		encoder.Put(digest, sizeof(digest));
		encoder.MessageEnd();
		toLowerCase(md5pwd);
		std::string params = "login="******"&password="******"tv/api/login", sessionKeyParam + "&" + params);
		if (res) {
			Json::Value root;
			Json::Reader reader;
			reader.parse(&response.memory[0],
					&response.memory[(long) response.size - 1], root);
			// Favorite channels
			channelList.clear();
			Json::Value favouriteChannels = root["favorite-channels"];
			unsigned int channelCount = favouriteChannels.size();
			for (unsigned int channel = 0; channel < channelCount; channel++) {
				Json::Value chId = favouriteChannels[channel]["channel"]["id"];
				channelList.push_back(chId.asUInt());
				std::cerr << "FilmonAPI: added channel " << chId.asUInt()
								<< std::endl;
			}
			clearResponse();
		}
	}
	return res;
}
Exemplo n.º 16
0
// Recursive function to convert JSON --> Lua table
static bool push_json_value_helper(lua_State *L, const Json::Value &value,
		int nullindex)
{
	switch(value.type()) {
		case Json::nullValue:
		default:
			lua_pushvalue(L, nullindex);
			break;
		case Json::intValue:
			lua_pushinteger(L, value.asInt());
			break;
		case Json::uintValue:
			lua_pushinteger(L, value.asUInt());
			break;
		case Json::realValue:
			lua_pushnumber(L, value.asDouble());
			break;
		case Json::stringValue:
			{
				const char *str = value.asCString();
				lua_pushstring(L, str ? str : "");
			}
			break;
		case Json::booleanValue:
			lua_pushboolean(L, value.asInt());
			break;
		case Json::arrayValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
				push_json_value_helper(L, *it, nullindex);
				lua_rawseti(L, -2, it.index() + 1);
			}
			break;
		case Json::objectValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
#ifndef JSONCPP_STRING
				const char *str = it.memberName();
				lua_pushstring(L, str ? str : "");
#else
				std::string str = it.name();
				lua_pushstring(L, str.c_str());
#endif
				push_json_value_helper(L, *it, nullindex);
				lua_rawset(L, -3);
			}
			break;
	}
	return true;
}
Exemplo n.º 17
0
/***************以下函数用于读取json静态数据***************/
unsigned int to_uint(const Json::Value& val)
{
    if ( val.isIntegral() )
        return val.asUInt();

    if ( val.isDouble() )
        return (unsigned int)val.asDouble();

    if ( val.isString() )
        return strtoul(val.asCString(), NULL, 0 );

    return 0;
}
Exemplo n.º 18
0
	sf::Color jsonNodeAs<sf::Color>(const Json::Value& node) {
		sf::Color c = sf::Color::White;
		if (node.isArray()) {
			c.r = static_cast<uint8_t>(node.get(0u, 255).asUInt());
			c.g = static_cast<uint8_t>(node.get(1u, 255).asUInt());
			c.b = static_cast<uint8_t>(node.get(2u, 255).asUInt());
			c.a = static_cast<uint8_t>(node.get(3u, 255).asUInt());
		} else if (node.isInt()) {
			unsigned int ic = node.asUInt();
			c.r = static_cast<uint8_t>(ic & 0xFF0000 >> 16);
			c.g = static_cast<uint8_t>(ic & 0xFF00 >> 8);
			c.b = static_cast<uint8_t>(ic & 0xFF);
			c.a = static_cast<uint8_t>(ic & 0xFF000000 >> 24);
		}
Exemplo n.º 19
0
void util::PrintJSONValue( Json::Value val ){
	if( val.isString() ) {
		printf( "string(%s)", val.asString().c_str() ); 
	} else if( val.isBool() ) {
		printf( "bool(%d)", val.asBool() ); 
	} else if( val.isInt() ) {
		printf( "int(%d)", val.asInt() ); 
	} else if( val.isUInt() ) {
		printf( "uint(%u)", val.asUInt() ); 
	} else if( val.isDouble() ) {
		printf( "double(%f)", val.asDouble() ); 
	} else {
		printf( "unknown type=[%d]", val.type() ); 
	}
}
unsigned int JsonParser::GetUint(const char* pName)
{
	if(!pName || (m_pRoot == NULL))
	{
		return 0;
	}

	Json::Value *pChild = GetChildByName(string(pName));
	if( pChild  == NULL)
	{
		return 0;
	}

	return pChild->asUInt();
}
long long JsonParser::GetUint64(const int nIndex)
{
	if((nIndex < 0) || (m_pRoot == NULL))
	{
		return 0;
	}

	Json::Value *pChild = GetChildByIndex(nIndex);
	if( pChild  == NULL)
	{
		return 0;
	}

	//todo
	return pChild->asUInt();
}
Exemplo n.º 22
0
	void Log::execute(fsm::Context * ctx, const log4cplus::Logger & log, const std::string & sessionId)const
	{
		std::string loginfo = m_strExpr;
		if (ctx && m_Type.compare("script") == 0) { 
			Json::Value jsonval = ctx->eval(m_strExpr, m_strFileName, m_lineNo/*,m_node*/);
			if (jsonval.isString() || jsonval.isBool() || jsonval.isNull()){
				loginfo = jsonval.asString();
			}
			else if (jsonval.isInt()){
				loginfo = std::to_string(jsonval.asInt());
			}
			else if (jsonval.isUInt()){
				loginfo = std::to_string(jsonval.asUInt());
			}
			else if (jsonval.isDouble()){
				loginfo = std::to_string(jsonval.asDouble());
			}
			else if (jsonval.isObject())
			{
				loginfo = jsonval.toStyledString();
			}
		}

		if (m_strLevel.compare("trace") == 0){
			LOG4CPLUS_TRACE(log, "." + sessionId,  m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else if (m_strLevel.compare("debug") == 0){
			LOG4CPLUS_DEBUG(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else if (m_strLevel.compare("info") == 0){
			LOG4CPLUS_INFO(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else if (m_strLevel.compare("warn") == 0){
			LOG4CPLUS_WARN(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else if (m_strLevel.compare("error") == 0){
			LOG4CPLUS_ERROR(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else if (m_strLevel.compare("fatal") == 0){
			LOG4CPLUS_FATAL(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
		else{

			LOG4CPLUS_INFO(log, "." + sessionId, m_strFileName << ":" << m_lineNo << "," << loginfo);
		}
	}
Exemplo n.º 23
0
bool FCII::ReceiveStream(UINT8* stream, int streamLen)
{
	SAFE_DELETEARRPTR(m_receivedstream);
	SAFE_DELETEARRPTR(m_sendedstream);
	m_hasbuilded = false;
	if (m_isweb)
	{


		string tmpStr = MyT2AA((LPCTSTR)stream);
		Json::Reader reader;
		Json::Value root;
		if (!reader.parse(tmpStr, root, false))
		{
			//解析失败
			return false;
		}
		Json::Value dataLen = root["DataLen"];
		streamLen = FCIICONTENTHEADLEN + dataLen.asUInt();
		m_receivedstream = new UINT8[streamLen];
		UINT8* streamPtr = m_receivedstream;
		*((UINT16*)streamPtr) = (UINT16)(root["Identify"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["CheckSum"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["MainCMD"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["SubCMD"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["IsRequest"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["ErrCode"].asUInt());
		streamPtr += UI16SIZE;
		*((UINT16*)streamPtr) = (UINT16)(root["DataLen"].asUInt());
		streamPtr += UI32SIZE;
		tmpStr = root["Data"].asString();
		UINT32 tmpLen = (UINT32)(root["DataLen"].asUInt());
		CopyMemory(streamPtr, tmpStr.data(), tmpLen);
	}
	else
	{
		m_receivedstream = new UINT8[streamLen];
		CopyMemory(m_receivedstream, stream, streamLen);
	}
	return Analyse(stream, streamLen, m_receivedcontent);
}
Exemplo n.º 24
0
 long JsonHelper::ToLong( const Json::Value& value, long defaultResult )
 {
     if ( value.isUInt() )
     {
         return  value.asUInt();
     }
     if ( value.isInt() )
     {
         return ((long)value.asInt());
     }
     if ( value.isDouble() )
     {
         return value.asDouble();
     }
     if ( value.isString() )
     {
         return Core::Convert::ToLong( value.asString() );
     }
     return defaultResult;
 }
Exemplo n.º 25
0
std::string getString (const Json::Value &value)
{
  switch (value.type () ) {
  case Json::ValueType::nullValue:
  case Json::ValueType::stringValue:
  case Json::ValueType::booleanValue:
    return value.asString();

  case Json::ValueType::intValue:
    return std::to_string (value.asInt () );

  case Json::ValueType::uintValue:
    return std::to_string (value.asUInt () );

  case Json::ValueType::realValue:
    return std::to_string (value.asDouble () );

  case Json::ValueType::arrayValue:
  case Json::ValueType::objectValue:
  default:
    return value.asString();
  }
}
void ApplyOverrides(std::string name, AtNode* node, std::vector<std::string> tags, ProcArgs & args)
{
   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.overrides.begin(); it!=args.overrides.end(); ++it)
   {
      Json::Value overrides;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          overrides = args.overrideRoot[*it];
        }
      }

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

          const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
          const AtParamEntry* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, attribute.c_str());

          if ( paramEntry != NULL && attribute!="invert_normals" || attribute == "matte")
          {

            Json::Value val = args.overrideRoot[*it][itr.key().asString()];
            if( val.isString() ) 
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            else if( val.isBool() )
            {
              if(attribute == "matte")
              {
                  AiMsgDebug("[ABC] adding enable_matte to %s", AiNodeGetName(node));
                  AddUserGeomParams(node,"enable_matte",AI_TYPE_BOOLEAN);
                  AiNodeSetBool(node,"enable_matte", val.asBool());
              }
              else
              {
                  AiNodeSetBool(node, attribute.c_str(), val.asBool());
              }
            }
            else if( val.isInt() ) 
            {
              //make the difference between Byte & int!
              int typeEntry = AiParamGetType(paramEntry);
              if(typeEntry == AI_TYPE_BYTE)
              { 
                if(attribute=="visibility")
                {
                  AtByte attrViz = val.asInt();
                  // special case, we must determine it against the general viz.
                  AtByte procViz = AiNodeGetByte( args.proceduralNode, "visibility" );
                  AtByte compViz = AI_RAY_ALL;
                  {
                    compViz &= ~AI_RAY_GLOSSY;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_GLOSSY;
                    else
                      attrViz &= ~AI_RAY_GLOSSY;
                    compViz &= ~AI_RAY_DIFFUSE;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_DIFFUSE;
                    else
                      attrViz &= ~AI_RAY_DIFFUSE;
                    compViz &= ~AI_RAY_REFRACTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFRACTED;
                    else
                      attrViz &= ~AI_RAY_REFRACTED;
                    compViz &= ~AI_RAY_REFLECTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFLECTED;
                    else
                      attrViz &= ~AI_RAY_REFLECTED;
                    compViz &= ~AI_RAY_SHADOW;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_SHADOW;
                    else
                      attrViz &= ~AI_RAY_SHADOW;
                    compViz &= ~AI_RAY_CAMERA;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_CAMERA;
                    else
                      attrViz &= ~AI_RAY_CAMERA;
                  }

                  AiNodeSetByte(node, attribute.c_str(), attrViz);
                }
                else
                  AiNodeSetByte(node, attribute.c_str(), val.asInt());
              }
              else 
                AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            else if( val.isDouble() ) 
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
          }
        }
      }

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

         }
      }
   }
}
Exemplo n.º 28
0
bool WsModulesLoader::load()
{
  Json::Value     root;
  Json::Reader    reader;
  std::ifstream   plugins(GlobalConfig::PluginsPropertiesPath.c_str(), std::ifstream::binary);
  bool bOk = reader.parse(plugins, root, false);
  if ( !bOk ) {
    LOG(DEBUG) << reader.getFormatedErrorMessages();
    return false;
  }
  //Json::Value          module = modules[iMod]; // crash
  Json::Value          modules = root["modules"];
  Json::Value::Members mbrs    = modules.getMemberNames();
  bool bDebug = false;
#if GDDEBUG == 1
  bDebug = true;
#endif
  for (int iMod = 0; iMod < mbrs.size(); ++iMod) {
    LOG(DEBUG) << "WsModulesLoader::load Loading module " << mbrs[iMod] << " debug mode = " << bDebug;
    Json::Value          module     = modules[mbrs[iMod]];
    Json::Value::Members attributes = module.getMemberNames();
    for (int iAtt = 0; iAtt < attributes.size(); ++iAtt) {
      if ( attributes[iAtt] == "soName" ) {
        std::string soName = module.get(attributes[iAtt], "").asString();
        if ( bDebug )
          boost::replace_first(soName, ".so", "d.so");
        // Important not RTLD_NOW because a derived module can also load a shared object
        //  and in this step is make in the dynlib initialization process (_init, _fini Ctor/Dtor)
        void* hndl = dlopen(soName.c_str(), RTLD_LAZY);
        if ( hndl == NULL ) {
          LOG(ERROR) << "WsModulesLoader::load dlopen error soName = " << soName <<  " error = " << dlerror();
          continue;
        }
        LOG(DEBUG) << "WsModulesLoader::load Loading module " << soName;
        pf_wsModule func = (pf_wsModule) dlsym(hndl, "buildModule");
        WsModule* pModule = func();
        WsModuleLoader* ml = new WsModuleLoader();
        ml->dlfcnHandler = hndl;
        ml->module = pModule;
        m_vModules.push_back(ml);
        pModule->setSoName(soName);
        //         std::string p = WApplication::instance()->appRoot() + WApplication::instance()->internalPath();
        //         pModule->setSysPath(p);
        for (int iAtt2 = 0; iAtt2 < attributes.size(); ++iAtt2) {
          if ( attributes[iAtt2] == "moduleName" ) {
            std::string moduleName = module.get(attributes[iAtt2], "").asString();
            pModule->setModuleName(moduleName);
          }
          if ( attributes[iAtt2] == "fileName" ) {
            std::string fileName = module.get(attributes[iAtt2], "").asString();
            pModule->setFileName(fileName);
          }
          if ( attributes[iAtt2] == "extension"  ||  attributes[iAtt2] == "extensions" ) {
            std::string extensions = module.get(attributes[iAtt2], "").asString();
            pModule->setExtensions(extensions);
          }
          if ( attributes[iAtt2] == "prefix" ) {
            std::string prefix = module.get(attributes[iAtt2], "").asString();
            pModule->setPrefix(prefix);
          }
          if ( attributes[iAtt2] == "hideImages" ) {
            std::string hideImages = module.get(attributes[iAtt2], "false").asString();
            if ( hideImages == "true" ) pModule->setHideImages(true);
          }
          if ( attributes[iAtt2] == "options" ) {
            Json::Value          options  =  module[attributes[iAtt2]];
            Json::Value::Members optAttrs =  options.getMemberNames();
            for (int iOpt = 0; iOpt < optAttrs.size(); ++iOpt) {
              Json::Value          val  = options[optAttrs[iOpt]];
              LOG(DEBUG) << "WsModuleLoader::load options " << optAttrs[iOpt] << " value = " << val.asString();
              if ( val.type() == Json::nullValue    ) continue;
              if ( val.type() == Json::intValue     )
                pModule->setOption(optAttrs[iOpt], val.asInt());
              if ( val.type() == Json::uintValue     )
                pModule->setOption(optAttrs[iOpt], val.asUInt());
              if ( val.type() == Json::realValue    )
                pModule->setOption(optAttrs[iOpt], val.asDouble());
              if ( val.type() == Json::stringValue  )
                pModule->setOption(optAttrs[iOpt], val.asString());
              if ( val.type() == Json::booleanValue )
                pModule->setOption(optAttrs[iOpt], val.asBool());
            }
          }
        }
        if ( module["loadOnStartup"] != Json::Value::null && module["loadOnStartup"].asBool()) {
          LOG(DEBUG) << "WsModuleLoader::load running Module " << pModule->moduleName();
          //fprintf(stderr, "WsModuleLoader :: running Module %s\n",pModule->moduleName().c_str());
          pModule->createContents();
          pModule->setLoaded();
        } else {
          LOG(DEBUG) << "WsModuleLoader::load running Module  else clause " <<  module["loadOnStartup"].asString();
          //fprintf(stderr, "WsModuleLoader ::else clause%s\n", module["loadOnStartup"].asString().c_str() );
        }
      }
    }
  }
  return true;
}
Exemplo n.º 29
0
void JsonSerializer::recurseWrite(Json::Value& jv, any& av)
{
	switch(jv.type())
	{
		case Json::nullValue:
			{
				av = any();
			}
			break;
		case Json::intValue:
			{
				av = jv.asInt();
			}
			break;
		case Json::uintValue:
			{
				av = jv.asUInt();
			}
			break;
		case Json::realValue:
			{
				av = jv.asDouble();
			}
			break;
		case Json::stringValue:
			{
				av = jv.asString();
			}
			break;
		case Json::booleanValue:
			{
				av = jv.asBool();
			}
			break;
		case Json::arrayValue:
			{
				av = any(list<any>());
				auto al = any_cast<list<any>&>(av);
				for(auto i = 0; i<jv.size(); ++i)
				{
					any tmp;
					recurseWrite(jv[i], tmp);
					al.push_back(tmp);
				}
			}
			break;
		case Json::objectValue:
			{
				av = any(list<pair<string, any> >());
				auto al = any_cast<list<pair<string, any> >&>(av);

				auto member = jv.getMemberNames();
				for (auto it = member.begin(); it != member.end(); it++)
				{
					any any;
					Json::Value& value = jv[(*it)];
					recurseWrite(value, any);
					al.push_back(make_pair(*it, any));
				}
			}
			break;
		default:
			break;
	}
}
Exemplo n.º 30
0
template<> ZEROBUF_INL uint32_t fromJSON( const Json::Value& json )
    { return json.asUInt(); }