Ejemplo n.º 1
0
Entity *EntityResourceManager::loadType(Json::Value &root)
{
	Json::Value entityType;
	entityType = root.get("type", NULL);
	if(entityType == NULL)
	{
		return NULL;
	}

	Entity *entityPtr = NULL;
	
	//read from file
	std::string type = entityType.asString();
	if(type.compare("player") == 0)
	{
		entityPtr = new Player();
		entityPtr->setType(PLAYER);
	}
	else if(type.compare("enemy") == 0)
	{
		entityPtr = new Enemy();
		entityPtr->setType(ENEMY);
	}
	else if(type.compare("damaging") == 0)
	{
		entityPtr = new DamagingEntity();
		entityPtr->setType(DAMAGING_ENTITY);
	}
	else if(type.compare("wall") == 0)
	{
		entityPtr = new Wall();
		entityPtr->setType(WALL);
	}
	else
	{
		//invalid type, stop right here criminal scum
		return NULL;
	}

	//if we got to here it was a valid type
	return entityPtr;
}
 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;
 }
Ejemplo n.º 3
0
Archivo: coder.cpp Proyecto: tuita/DOMQ
int JsonCoder::Encode(char* buf, size_t len, const Message* message) const
{
    Json::Value obj;
    if(0 != message->JsonEncode(obj))
    {
        LOG_ERROR("message:[%s] jsonencode error", message->ToString().c_str());
        return -1;
    }
    obj["_msg_"] = Json::Value(message->GetTypeName().c_str());
    const std::string& data = obj.asString();
    if (data.size() > len)
    {
        LOG_ERROR("data len:%zd, buf len:%zd", data.size(), len);
        return -1;
    }
    int size = htonl(data.size()+4);
    memcpy(buf, (const char*)&size, 4);
    memcpy(buf+4, data.c_str(), data.size());
    return 4+data.size();
}
Ejemplo n.º 4
0
void PrefabEntityParser::parse(Entity* entity, const Json::Value& node) {
  String path = node.asString();
  String fullPath = CCFileUtils::fullPathFromRelativePath(path.c_str());
  String json = String::fromFile(fullPath);
  
  Json::Reader reader;
  Json::Value root;
  
  reader.parse(json.str(), root);
  
  Json::Value::Members members = root.getMemberNames();
  
  for (int i = 0; i < members.size(); ++i) {
    shared_ptr<EntityParser> parser = EntityParser::parser(members[i]);
    Json::Value data = root[parser->type().c_str()];
    parser->parse(entity, data);
  }
  
  entity->prefabOverride();
}
Ejemplo n.º 5
0
std::string Channel::MethodName(std::string _mode,Json::Value _method)
{
    std::string mode="";
    std::string method="";
    std::string mms=_method.asString();
    int pos = mms.find_first_of('.');
    if(std::string::npos== pos){
        LOGE("method:find error,%d",pos);
        return method;
    }
    mode = mms.erase(pos);
    if(mode == _mode){
      method = mms.erase(0,pos+1);
      LOGI("find method:%s",method.c_str());
    }
    else{
        LOGE("mode(%s) is not match mode(%s)",mode.c_str(),_mode.c_str());
    }
    return method;
}
Ejemplo n.º 6
0
            // Read a string 
            std::string string(
                Optizelle::Messaging const & msg,
                Json::Value const & json,
                std::string const & name
            ) {
                // Set the error message
                std::string const err_msg = "Invalid JSON parameter: "
                    + name + " is not a valid parameter.";

                // As long as we have an unsigned integer, grab it
                if(json.isString())
                    return json.asString();

                // Anything else is an error
                else
                    msg.error(err_msg);

                // We should not hit this point
                throw;
            }
Ejemplo n.º 7
0
void LCDCore::ChangeLayout() {
    if(is_transitioning_) {
        //timer_->start(100);
        return;
    }
    LCDError("ChangeLayout");
    Json::Value *t = CFG_Fetch_Raw(CFG_Get_Root(), 
        current_layout_ + ".transition");
    if(!t or transitions_off_) {
        StopLayout(current_layout_);
        StartLayout();
    } else {
        StartTransition(t->asString());
        delete t;
        if(type_ & LCD_TEXT) {
            LCDText *text = ((LCDText *)lcd_);
            text->CleanBuffer(text->LayoutFB);
        }
    }
}
Ejemplo n.º 8
0
void QuestionRequest::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    

    
    if ( root.isObject() && root.isMember("msg") ) {
        tmp = root["msg"];
        if ( !tmp.isNull() )
        {
            msg = tmp.asString();
        }
    }

    
    if ( root.isObject() && root.isMember("status") ) {
        tmp = root["status"];
        if ( !tmp.isNull() )
        {
            status = tmp.asInt();
        }
    }

    
    
    if ( root.isObject() && root.isMember("data") ) {
        const Json::Value &array_data = root["data"];
        if ( !array_data.isNull() )
        {
            int size = array_data.size();
            for ( int i = 0; i < size; i++ ) {
                CheckUserNameRequestQuestion item;
                item.decode_from_json_object(array_data[i]);
                data.push_back(item);
            }
        }
    }
    
    
}
Ejemplo n.º 9
0
void BuyedListRequestData::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    
    if ( root.isObject() && root.isMember("total") ) {
        tmp = root["total"];
        if ( !tmp.isNull() )
        {
            total = tmp.asString();
        }
    }

    

    

    
    
    if ( root.isObject() && root.isMember("contentUuid") ) {
        const Json::Value map_contentUuid = root["contentUuid"];
        if ( !map_contentUuid.isNull() ) {
            for( Json::ValueIterator it = map_contentUuid.begin(); it != map_contentUuid.end(); ++it ) {
            
                std::string key = it.key().asString();
                contentUuid[key] = map_contentUuid[key].asString();
            }
        }
    }   
    
    if ( root.isObject() && root.isMember("buyCount") ) {
        const Json::Value map_buyCount = root["buyCount"];
        if ( !map_buyCount.isNull() ) {
            for( Json::ValueIterator it = map_buyCount.begin(); it != map_buyCount.end(); ++it ) {
            
                std::string key = it.key().asString();
                buyCount[key] = map_buyCount[key].asInt();
            }
        }
    }   
}
Ejemplo n.º 10
0
k8s_pair_list k8s_component::extract_object(const Json::Value& object, const std::string& name)
{
	k8s_pair_list entry_list;
	if(!object.isNull())
	{
		Json::Value entries = object[name];
		if(!entries.isNull())
		{
			Json::Value::Members members = entries.getMemberNames();
			for (auto& member : members)
			{
				Json::Value val = entries[member];
				if(!val.isNull())
				{
					entry_list.emplace_back(k8s_pair_t(member, val.asString()));
				}
			}
		}
	}
	return entry_list;
}
Ejemplo n.º 11
0
string UserHandler::Update_ExistentUserChecked(string identifier, Json::Value rootToken, string json, User user){
	if(Token::IsGuidValid(identifier, rootToken.asString())){
		std::set<string> ignoredAttributes;
		ignoredAttributes.insert("identifier");
		ignoredAttributes.insert("md5");
		ignoredAttributes.insert("root");
		ignoredAttributes.insert("quotaLimitMB");
		ignoredAttributes.insert("isActive");

		user.SetAllAttributes(json, ignoredAttributes);

		user.Save();

		Log::insert(Log::TYPE_INFORMATION, "Actualizado exitosamente el usuario " + identifier);
		return "{ \"result\" : \"OK\" ,  \"message\" : \"\" }";
	}
	else{
		Log::insert(Log::TYPE_ERROR, "Error en la actualización del usuario " + identifier + ". Token inválido.");
		return "{ \"result\" : \"ERROR\" ,  \"message\" : \"Invalid token\" }";
	}
}
Ejemplo n.º 12
0
 Json::Value resolvePossibleRef(Json::Value const &input,
                                bool stringAcceptableResult,
                                std::vector<std::string> const &searchPath) {
     Json::Value ret{Json::nullValue};
     if (input.isString()) {
         ret = loadFromFile(input.asString(), searchPath);
         if (ret.isNull() && stringAcceptableResult) {
             ret = input;
         }
         return ret;
     }
     if (input.isObject() && input.isMember("$ref")) {
         /// @todo remove things after the filename in the ref.
         ret = loadFromFile(input["$ref"].asString(), searchPath);
         if (!ret.isNull()) {
             return ret;
         }
     }
     ret = input;
     return ret;
 }
Ejemplo n.º 13
0
State const* MessageFactory::ParseGameBoardStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");

    Json::Value mine = states.get(USERNAME, "not found");
    int piece = mine.get("piece_number", -1).asInt();
    Json::Value boardV = mine.get("board_state", "0");
    if (boardV.asString().size() != BOARD_DESC_SIZE) {
        return new ErrorState("Invalid board description.");
    }
    char* board = new char[BOARD_DESC_SIZE];
    memcpy((void*)board, (void*)boardV.asCString(), BOARD_DESC_SIZE);
    Json::Value clearedV = mine.get("cleared_rows", "not found");
    std::vector<int>* cleared = new std::vector<int>();
    for (unsigned i = 0; i < clearedV.size(); ++i) {
        cleared->push_back(clearedV[i].asInt());
    }

    return new GameBoardState(sequence, timestamp, board, piece, cleared);
}
Ejemplo n.º 14
0
 void LuaModule::pushValue(const Json::Value &val, lua_State * stack) {
     if (val.isIntegral()) {
         lua_pushinteger(stack, val.asInt());
     } else if (val.isDouble()) {
         lua_pushnumber(stack, val.asDouble());
     } else if (val.isBool()) {
         lua_pushboolean(stack, val.asBool());
     } else if (val.isString()) {
         lua_pushstring(stack, val.asString().c_str());
     } else if (val.isNull()) {
         //lua_pushstring(stack, val.asString().c_str());
         lua_pushnil(stack);
     } else {
         lua_pop(stack, 1);
         std::stringstream ss;
         ss << val.type();
         std::string typeNum;
         ss >> typeNum;
         throw std::runtime_error("Value type error: value of type " + typeNum);
     }
 }
Ejemplo n.º 15
0
	void _Deserialize(const AuthorizedObject &parent_obj, const Json::Value &json)
	{
		if(!json.isConvertibleTo(Json::stringValue))
			throw UnexpectedException("!json.isConvertibleTo(Json::stringValue)");

		const std::string &str = json.asString();

		bool found = false;

		// Hack: This is nasty, but required to do a complete iteration. Hopefully, we never have to go over the int limit!
		for(int s = (int)none; s < (int)count; ++s)
		{
			if(stricmp(str.c_str(), str_array[s]) == 0)
			{
				t_ = (T)s;
				break;
			}
		}

		if(!found)
			throw UnexpectedException("!found");
	}
Ejemplo n.º 16
0
//////////////////////////////////////////////////////////////////////////
// serialisePointer
//virtual
Json::Value SeJsonWriter::serialisePointer( void* pData, const ReClass* pClass, BcU32 ParentFlags )
{
	if( pData != nullptr )
	{
		// Setup Json::Value for this class.
		Json::Value PointerValue = ObjectCodec_->serialiseAsStringRef( pData, pClass );
	
		// Check if we can up cast.
		if( pClass->hasBaseClass( ReObject::StaticGetClass() ) )
		{
			ReObject* Object = reinterpret_cast< ReObject* >( pData );
			pClass = Object->getClass();
		}
			
		// Add to list to serialise if it hasn't been added.
		if( ObjectCodec_->shouldSerialiseContents( pData, pClass ) )
		{
			if( ( ParentFlags & bcRFF_OWNER ) == 0 )
			{
				auto ClassToSerialise = SerialiseClass( pData, pClass );
				if( std::find( SerialiseClasses_.begin(), SerialiseClasses_.end(), ClassToSerialise ) == SerialiseClasses_.end() )
				{
					SerialiseClasses_.push_back( ClassToSerialise );
				}
			}
			else
			{	
				auto ClassValue = serialiseClass( pData, pClass, 0, true );
				ObjectValueMap_[ PointerValue.asString() ] = ClassValue;
			}
		}

		return PointerValue;
	}

	return Json::nullValue;
}
Ejemplo n.º 17
0
osc::OutboundPacketStream LogReplayer::constructSyncArg(char* buffer,std::string name, int index, Json::Value value)
{
    //    char buffer[1024];
    osc::OutboundPacketStream p(buffer,1024);
    p << osc::BeginMessage("/sA");
    p << client->getServerPassword().toStdString().c_str();
    p << name.c_str();
    p << index;
    if(value.isDouble())
    {
        p << (float)value.asDouble();
    }
    else if(value.isString())
    {
        p << value.asString().c_str();
    }
    else if(value.isInt())
    {
        p << value.asInt();
    }
    p << osc::EndMessage;

    return p;
}
Ejemplo n.º 18
0
 Layout::Parameter::Parameter(const Json::Value &js)
 {
     switch (js.type()) {
         case Json::ValueType::stringValue:
         {
             vsson::VSSObject vsson = vsson::VSSParser::parse(js.asString());
             json = Utils::jsonFromVsson(vsson);
         }
             break;
             
         case Json::ValueType::arrayValue:
         {
             for (uint i = 0; i < js.size(); ++i)
             {
                 this->json[StringUtils::format("%u", i)] = json[i];
             }
         }
             break;
             
         default:
             json = js;
             break;
     }
 }
Ejemplo n.º 19
0
    Ogre::Vector3 JsonUtils::asVector3(Json::Value const &value, const Ogre::Vector3 &defaultValue)
    {
        if(value.isString())
        {
            auto const &s = value.asString();

            if(Ogre::StringConverter::isNumber(s))
            {
                float f = Ogre::StringConverter::parseReal(s);
                return Ogre::Vector3(f, f, f);
            }
            else
            {
                return Ogre::StringConverter::parseVector3(s);
            }
        }
        else if(value.isNumeric())
        {
            float f = value.asFloat();
            return Ogre::Vector3(f, f, f);
        }

        return defaultValue;
    }
Ejemplo n.º 20
0
boost::shared_ptr< ResourceObject > ResourceObjectManager::loadObject(const std::string& currentPath, const Json::Value& object)
{
    if (object.isNull())
        return boost::shared_ptr< ResourceObject >();

    if (object.isString())
    {
        std::string path = object.asString();
        if (path[0] == ':')
        {
            m_objectFiles[currentPath] = path.substr(1);
            return boost::shared_ptr< ResourceObject >();
        }
        else
        {
            return getResourceObject(path);
        }
    }
    if (!object.isMember("@type"))
    {
        Log::error() << "[ROM] Invalid JSON object (no @type field)";
        return boost::shared_ptr< ResourceObject >();
    }
    std::string type = object.get("@type", "").asString();

    auto fi = m_objectFactories.find(type);
    if (fi == m_objectFactories.end())
    {
        Log::warning() << "[ROM] No object loader found for type " << type;
        return boost::shared_ptr< ResourceObject >();
    }
    boost::shared_ptr< ResourceObject > o = (*(fi->second))(currentPath, object, *this);
    if (o)
        m_objects[currentPath] = o;
    return o;
}
Ejemplo n.º 21
0
bool Application::LoadProject(std::string a_file)
{
  ClearProject();

  std::ifstream fs;
  fs.open(a_file);
  if (!fs.good())
  {
    printf("Failed to open file '%s'!\n", a_file.c_str());
    return false;
  }

  Json::Value root;
  fs >> root;

  Json::Value node = root["State"];
  if (!node.isNull())
  {
    Json::Value val = node["useUpdaterColor"];
    if (!val.isNull()) m_projData.parSysOpts[0].useUpdaterColor = val.asBool();

    val = node["useUpdaterRelativeForce"];
    if (!val.isNull()) m_projData.parSysOpts[0].useUpdaterRelativeForce = val.asBool();

    val = node["useUpdaterSize"];
    if (!val.isNull()) m_projData.parSysOpts[0].useUpdaterSize = val.asBool();
  }

  InitParticleSystem();

  node = root["Emitters"];
  if (!node.isNull())
  {
    for (int i = 0; i < (int)node.size(); ++i)
    {
      EDataItem e;
      Json::Value val = node[i]["ID"];
      if (!val.isNull()) e.first.ID = val.asInt();

      val = node[i]["type"];
      if (!val.isNull()) e.first.type = val.asInt();

      val = node[i]["on"];
      if (!val.isNull()) e.first.on = val.asBool();

      val = node[i]["posGenMethod"];
      if (!val.isNull()) e.first.posGenMethod = val.asInt();

      val = node[i]["velGenMethod"];
      if (!val.isNull()) e.first.velGenMethod = val.asInt();

      val = node[i]["relativeForce"];
      if (!val.isNull()) e.first.relativeForce = val.asFloat();

      val = node[i]["velocity"];
      if (!val.isNull()) e.first.velocity = val.asFloat();

      val = node[i]["rate"];
      if (!val.isNull()) e.first.rate = val.asFloat();

      val = node[i]["life"];
      if (!val.isNull()) e.first.life = val.asFloat();

      val = node[i]["transform"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 7) memcpy(e.first.transform, t.data(), 7 * sizeof(float));
      }

      val = node[i]["boxDim"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 3) memcpy(e.first.boxDim, t.data(), 3 * sizeof(float));
      }

      val = node[i]["velCone"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 3) memcpy(e.first.velCone, t.data(), 3 * sizeof(float));
      }

      val = node[i]["colors"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 8) memcpy(e.first.colors, t.data(), 8 * sizeof(float));
      }

      val = node[i]["sizes"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 2) memcpy(e.first.sizes, t.data(), 2 * sizeof(float));
      }

      memcpy(&e.second, &e.first, sizeof(EmitterData));
      m_projData.eData.push_back(e);
      m_IDManager.MarkAsUsed(e.first.ID);
      EmitterFactory eFact;
      m_particleSystem.AddEmitter(e.first.ID, eFact(e.first));
      m_projData.emitterFocus = 0;
    }
  }

  node = root["Attractors"];
  if (!node.isNull())
  {
    for (int i = 0; i < (int)node.size(); ++i)
    {
      ADataItem a;
      Json::Value val;
      val = node[i]["ID"];
      if (!val.isNull()) a.first.ID = val.asInt();

      val = node[i]["attenuationMethod"];
      if (!val.isNull()) a.first.attenuationMethod = val.asInt();

      val = node[i]["maxAppliedAccelMag"];
      if (!val.isNull()) a.first.maxAppliedAccelMag = val.asFloat();

      val = node[i]["show"];
      if (!val.isNull()) a.first.show = val.asBool();

      val = node[i]["strength"];
      if (!val.isNull()) a.first.strength = val.asFloat();

      val = node[i]["type"];
      if (!val.isNull()) a.first.type = val.asInt();

      val = node[i]["transform"];
      if (!val.isNull())
      {
        std::vector<float> t;
        Dg::StringToNumberList(val.asString(), ',', std::dec, t);
        if (t.size() == 6) memcpy(a.first.transform, t.data(), 6 * sizeof(float));
      }

      memcpy(&a.second, &a.first, sizeof(AttractorData));
      m_projData.aData.push_back(a);
      m_IDManager.MarkAsUsed(a.first.ID);
      AttractorFactory aFact;
      m_particleSystem.AddUpdater(a.first.ID, aFact(a.first));
      m_projData.attrFocus = 0;
    }
  }

  UpdateProjectTitle(a_file);
  m_projData.dirty = false;

  return true;
}
Ejemplo n.º 22
0
void Config::load(SceneRenderer * sceneRenderer, Manager * manager) {
    Json::Value root;   // will contains the root value after parsing.
	Json::Reader reader;

	std::ifstream file;
	file.open(fileName);
    bool parsingSuccessful = reader.parse(file, root, false);
	file.close();
	if(!parsingSuccessful) {
		// report to the user the failure and their locations in the document.
		System::Console::WriteLine("Failed to parse configuration\n");
		System::Console::WriteLine(gcnew System::String(reader.getFormatedErrorMessages().c_str()));
		throw std::runtime_error("Failed to parse configuration file: "+fileName);
	}

	Json::Value sceneJSON = root.get("scene", NULL);
	Scene * scene = sceneRenderer->getScene();
	Json::Value bgColorJSON = sceneJSON.get("backgroundColor", NULL);
	if(bgColorJSON != NULL) {
		scene->setBackgroundColor(jsonToColor(bgColorJSON));
	}

	Json::Value lightsJSON = sceneJSON.get("lights", NULL);
	if(lightsJSON != NULL) {
		Json::Value::Members lightsName = lightsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = lightsName.begin(); it != lightsName.end(); it++) {
			std::string lightName = *it;
			Json::Value lightJSON = lightsJSON[lightName];
			RGBColor lightColor = jsonToColor(lightJSON["color"]);
			LightSource * light;
			std::string lightTypeStr = lightJSON["type"].asString();
			if(lightTypeStr == "AmbientLightSource") {
				light = new AmbientLightSource(lightColor);
			} else if(lightTypeStr == "PointLightSource") {
				light = new PointLightSource(jsonToP3(lightJSON["position"]), lightColor);
				Json::Value specularCoefJSON = lightJSON.get("specularCoef", NULL);
				PointLightSource * pLight = static_cast<PointLightSource*>(light);
				if(specularCoefJSON != NULL) {
					pLight->setSpecularCoef(specularCoefJSON.asDouble());
				}
				Json::Value specularExpJSON = lightJSON.get("specularExponent", NULL);
				if(specularExpJSON != NULL) {
					pLight->setSpecularExponent(specularExpJSON.asDouble());
				}
			}
			Json::Value diffuseCoefJSON = lightJSON.get("diffuseCoef", NULL);
			if(diffuseCoefJSON != NULL) {
				light->setDiffuseCoef(diffuseCoefJSON.asDouble());
			}
			//scene->addLightSource(light);
			manager->getLightSources()->add(lightName, light, lightTypeStr);
		}
	}

	Json::Value objectsJSON = sceneJSON.get("objects", NULL);
	if(objectsJSON != NULL) {
		Json::Value::Members objectsName = objectsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = objectsName.begin(); it != objectsName.end(); it++) {
			std::string objectName = *it;
			Json::Value object3DJSON = objectsJSON[objectName];
			Object3D * object3D;
			std::string oject3DTypeStr = object3DJSON["type"].asString();
			if(oject3DTypeStr == "Sphere") {
				object3D = new Sphere(jsonToP3(object3DJSON["center"]),
									  object3DJSON["radius"].asDouble());
			} else if(oject3DTypeStr == "Plane") {
				
				if(object3DJSON.get("u", NULL) != NULL) {
					object3D = new Plane(jsonToP3(object3DJSON["p"]),
									 jsonToP3(object3DJSON["u"]),
									 jsonToP3(object3DJSON["v"]));
				} else {
					object3D = new Plane(jsonToP3(object3DJSON["p"]),
										 jsonToP3(object3DJSON["normal"]));
				}
			} else if(oject3DTypeStr == "Triangle") {
				object3D = new Triangle(jsonToP3(object3DJSON["A"]),
									    jsonToP3(object3DJSON["B"]),
										jsonToP3(object3DJSON["C"]));
			}
			//scene->addObject3D(object3D);
			manager->getObjects3D()->add(objectName, object3D, oject3DTypeStr);
		}
	}

	Json::Value polyhedraJSON = sceneJSON.get("polyhedra", NULL);
	if(polyhedraJSON != NULL) {
		Json::Value::Members polyhedraName = polyhedraJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = polyhedraName.begin(); it != polyhedraName.end(); it++) {
			std::string objectName = *it;
			Json::Value polyhedronJSON = polyhedraJSON[objectName];
			Polyhedron * polyhedron;
			std::string polyhedronTypeStr = polyhedronJSON["type"].asString();
			if(polyhedronTypeStr == "Parallelepiped") {
				polyhedron = new Parallelepiped(jsonToP3(polyhedronJSON["A"]),
												jsonToP3(polyhedronJSON["B"]),
												jsonToP3(polyhedronJSON["C"]),
												jsonToP3(polyhedronJSON["D"]));
			} else if(polyhedronTypeStr == "Maya") {
				std::vector<Triangle*> triangles;
				std::string filename = polyhedronJSON["FileName"].asString();
				Json::Value pJSON = polyhedronJSON.get("p", NULL);
				P3 centerObj(0,0,0);
				if(pJSON != NULL) centerObj = jsonToP3(polyhedronJSON["p"]);
				Json::Value scaleJSON = polyhedronJSON.get("scale", NULL);
				double scale = 1.0;
				if(scaleJSON != NULL) scale = scaleJSON.asDouble();
				parseObjFile(filename, &triangles, centerObj, scale);
				polyhedron = new Polyhedron(triangles);
			} else continue;
			/*std::vector<Triangle*> triangles = polyhedron->getTriangles();
			for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) {
				scene->addObject3D(*it);
			}*/
			manager->getPolyhedra()->add(objectName, polyhedron, polyhedronTypeStr);
		}
	}

	Json::Value texturesJSON = root.get("textures", NULL);
	if(texturesJSON != NULL) {
		Json::Value::Members texturesName = texturesJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = texturesName.begin(); it != texturesName.end(); it++) {
			std::string textureName = *it;
			Json::Value textureJSON = texturesJSON[textureName];
			Texture * texture = new Texture(textureJSON["FileName"].asString());
			manager->getTextures()->add(textureName, texture);
		}
	}

	Json::Value sceneRendererJSON = root.get("sceneRenderer", NULL);
	if(sceneRendererJSON == NULL) 
		throw std::runtime_error("sceneRenderer not defined in "+fileName);
	Json::Value cameraJSON = sceneRendererJSON["camera"];
	Camera * camera = new Camera(jsonToP3(cameraJSON["position"]),
								 jsonToP3(cameraJSON["direction"]),
								 cameraJSON.get("rotation", 0).asDouble());
	sceneRenderer->setCamera(camera);
	sceneRenderer->setCameraScreenDist(sceneRendererJSON.get("cameraScreenDist", 200).asDouble());
	manager->getCameras()->add("camera1", camera);

	std::string methodType = sceneRendererJSON["method"].get("type", "OrthographicProjection").asString();
	RenderingMethod * renderingMethod = NULL;
	if(methodType == "OrthographicProjection") {
		renderingMethod = new OrthographicProjection();
	} else if(methodType == "RayCasting") {
		renderingMethod = new RayCasting();
	} else if(methodType == "RayTracing") {
		renderingMethod = new RayTracing();
	}
	if(renderingMethod != NULL)
		sceneRenderer->setRenderingMethod(renderingMethod);

	Json::Value modelsJSON = sceneRendererJSON.get("models", NULL);
	if(modelsJSON != NULL) {
		Json::Value::Members modelsName = modelsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = modelsName.begin(); it != modelsName.end(); it++) {
			std::string modelName = *it;
			Json::Value modelJSON = modelsJSON[modelName];
			Json::Value modelTypeJSON = modelJSON.get("type", NULL);
			if(modelTypeJSON != NULL) {
				std::string modelTypeStr = modelTypeJSON.asString();
				Model * model;
				if(modelTypeStr == "SphereModel") {
					model = new SphereModel();
				} else if( modelTypeStr == "PlaneModel"	|| modelTypeStr == "TriangleModel") {
					model = new PlaneModel();
				} else if(modelTypeStr == "PolyhedronModel" || modelTypeStr == "ParallelepipedModel" || modelTypeStr == "MayaModel") {
					model = new PolyhedronModel();
				}
				Json::Value textureJSON = modelJSON.get("texture", NULL);
				if(textureJSON != NULL) {
					model->setTexture(manager->getTextures()->get(textureJSON.asString()));
				}
				Json::Value colorJSON = modelJSON.get("color", NULL);
				if(colorJSON != NULL) {
					model->setColor(jsonToColor(colorJSON));
				}
				Json::Value bumpJSON = modelJSON.get("bump", NULL);
				if(bumpJSON != NULL) {
					model->setBump(manager->getTextures()->get(bumpJSON.asString()));
				}
				Json::Value materialJSON = modelJSON.get("material", NULL);
				if(materialJSON != NULL) {
					model->setMaterial(jsonToMaterial(materialJSON));
				}
				Json::Value textureScaleJSON = modelJSON.get("textureScale", NULL);
				if(textureScaleJSON != NULL) {
					model->setTextureScale(textureScaleJSON.asDouble());
				}
				manager->getModels()->add(modelName, model);
				Json::Value modelObjectsJSON = modelJSON.get("objects", NULL);
				if(modelObjectsJSON != NULL) {
					for(unsigned int i=0; i < modelObjectsJSON.size(); i++) {
						std::string objectName = modelObjectsJSON[i].asString();
						Object3D * object3D = manager->getObjects3D()->get(objectName);
						Polyhedron * polyhedron = manager->getPolyhedra()->get(objectName);
						if(object3D != NULL) {
							sceneRenderer->getObject3DRenderer(object3D)->setModel(model);
						} else if(polyhedron != NULL) {
							std::vector<Triangle*> triangles = polyhedron->getTriangles();
							for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) {
								sceneRenderer->getObject3DRenderer(*it)->setModel(model);
							}
						} else continue;
					}
				}
			}
		}
	}
}
Ejemplo n.º 23
0
SWHardRef<SWSpriteAnimation> SWSpriteAnimation::create( const tstring& json )
{
	Json::Reader reader;
	Json::Value root;

	if ( !reader.parse( json, root ) ) return NULL;

	Json::Value sprites = root.get( "sprites", Json::nullValue );
	if ( sprites == Json::nullValue ) return NULL;

	Json::Value sequences = root.get( "sequences", Json::nullValue );
	if ( sequences == Json::nullValue ) return NULL;

	ttable<tstring, SWHardRef<SWSprite> > spriteTable;
	for ( tuint i = 0 ; i < sprites.size() ; ++i )
	{
		Json::Value info = sprites.get( (Json::Value::UInt)i, Json::nullValue );
		if ( info == Json::nullValue ) continue;
		if ( info.type() != Json::objectValue ) continue;

		Json::Value name = info.get( "name", Json::nullValue );
		if ( name == Json::nullValue ) continue;
		if ( name.type() != Json::stringValue ) continue;

		Json::Value texFile = info.get( "texture", Json::nullValue );
		if ( texFile == Json::nullValue ) continue;
		if ( texFile.type() != Json::stringValue ) continue;
		
		Json::Value rect = info.get( "rect", Json::nullValue );
		if ( rect == Json::nullValue ) continue;
		if ( rect.type() != Json::arrayValue ) continue;
		if ( rect.size() != 4 ) continue;

		Json::Value offsetX = rect.get( (Json::Value::UInt)0, Json::nullValue );
		if ( offsetX == Json::nullValue ) continue;
		
		Json::Value offsetY = rect.get( (Json::Value::UInt)1, Json::nullValue );
		if ( offsetY == Json::nullValue ) continue;
		
		Json::Value width = rect.get( (Json::Value::UInt)2, Json::nullValue );
		if ( width == Json::nullValue ) continue;
		
		Json::Value height = rect.get( (Json::Value::UInt)3, Json::nullValue );
		if ( height == Json::nullValue ) continue;

		SWHardRef<SWTexture> texture = SWAssets.loadTexture( texFile.asString() );
		if ( texture.isValid() == false ) continue;

		SWHardRef<SWSprite> sprite = new SWSprite( texture, offsetX.asInt(), offsetY.asInt(), width.asInt(), height.asInt() );

		spriteTable.insert( std::make_pair( name.asString(), sprite ) );
	}

	SWHardRef<SWSpriteAnimation> animation = new SWSpriteAnimation();
	animation()->m_sequences.reserve( sequences.size() );
	for ( tuint i = 0 ; i < sequences.size() ; ++i )
	{
		Json::Value info = sequences.get( (Json::Value::UInt)i, Json::nullValue );
		if ( info == Json::nullValue ) continue;
		if ( info.type() != Json::objectValue ) continue;

		Json::Value name = info.get( "name", Json::nullValue );
		if ( name == Json::nullValue ) continue;
		if ( name.type() != Json::stringValue ) continue;

		Json::Value delay = info.get( "delay", Json::nullValue );
		if ( delay == Json::nullValue ) continue;
		if ( delay.type() != Json::realValue ) continue;

		Json::Value sprites = info.get( "sprites", Json::nullValue );
		if ( sprites == Json::nullValue ) continue;
		if ( sprites.type() != Json::arrayValue ) continue;

		SWHardRef<SWSpriteSequence> sequence = new SWSpriteSequence();
		sequence()->setName( name.asString() );
		sequence()->setDelayPerUnit( (float)delay.asDouble() );

		for ( tuint j = 0 ; j < sprites.size() ; ++j )
		{
			Json::Value spriteName = sprites.get( (Json::Value::UInt)j, Json::nullValue );
			if ( spriteName == Json::nullValue ) continue;
			if ( spriteName.type() != Json::stringValue ) continue;

			ttable<tstring, SWHardRef<SWSprite> >::iterator itor = spriteTable.find( spriteName.asString() );
			if ( itor == spriteTable.end() ) continue;

			sequence()->addSprite( itor->second() );
		}

		animation()->m_sequences.push_back( sequence() );
	}

	return animation;
}
Ejemplo n.º 24
0
static void
printValueTree(FILE* fout, Json::Value& value, const JSONCPP_STRING& path = ".") {
  if (value.hasComment(Json::commentBefore)) {
    fprintf(fout, "%s\n", value.getComment(Json::commentBefore).c_str());
  }
  switch (value.type()) {
  case Json::nullValue:
    fprintf(fout, "%s=null\n", path.c_str());
    break;
  case Json::intValue:
    fprintf(fout,
            "%s=%s\n",
            path.c_str(),
            Json::valueToString(value.asLargestInt()).c_str());
    break;
  case Json::uintValue:
    fprintf(fout,
            "%s=%s\n",
            path.c_str(),
            Json::valueToString(value.asLargestUInt()).c_str());
    break;
  case Json::realValue:
    fprintf(fout,
            "%s=%s\n",
            path.c_str(),
            normalizeFloatingPointStr(value.asDouble()).c_str());
    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());
    Json::ArrayIndex size = value.size();
    for (Json::ArrayIndex index = 0; index < size; ++index) {
      static char buffer[16];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
      sprintf_s(buffer, sizeof(buffer), "[%d]", index);
#else
      snprintf(buffer, sizeof(buffer), "[%d]", index);
#endif
      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());
    JSONCPP_STRING suffix = *(path.end() - 1) == '.' ? "" : ".";
    for (Json::Value::Members::iterator it = members.begin();
         it != members.end();
         ++it) {
      const JSONCPP_STRING name = *it;
      printValueTree(fout, value[name], path + suffix + name);
    }
  } break;
  default:
    break;
  }

  if (value.hasComment(Json::commentAfter)) {
    fprintf(fout, "%s\n", value.getComment(Json::commentAfter).c_str());
  }
}
void RemoveDefaultExposureLimitForMarketGroupsResponse::fromJson(const Json::Value& json) {
    if (validateJson(json)) {
        response = json.asString();
    }
}
Ejemplo n.º 26
0
//////////////////////////////////////////////////////////////////////////
// internalImportObject
BcBool CsCore::internalImportObject( const Json::Value& Object, CsResourceRef<>& Handle, CsDependancyList* pDependancyList, BcBool ForceImport )
{
	BcScopedLock< BcMutex > Lock( ContainerLock_ );

	// If we pass in a string value, call into the importResource that takes a file name.
	// If we pass in an object value, load it from that.
	if( Object.type() == Json::stringValue )
	{
		// We don't pass the dependancy list in if it's a file.
		return internalImportResource( Object.asString(), Handle, NULL, ForceImport );
	}
	else if( Object.type() == Json::objectValue )
	{
		Json::Value::Members Members = Object.getMemberNames();
		
		if( Members.size() == 1 )
		{
			const std::string& Type = Members[ 0 ];
			const Json::Value& Resource = Object[ Type ];
			
			// If the resource is a string, it's an alias - so we need to load the appropriate file.
			// If the resource is an object, then do appropriate loading.
			if( Resource.type() == Json::stringValue )
			{
				return internalImportResource( Resource.asString(), Handle, pDependancyList, ForceImport );
			}
			else if( Resource.type() == Json::objectValue )
			{
				// Check the resource has a name, and it's a string.
				if( Resource.isMember( "name" ) && Resource[ "name" ].type() == Json::stringValue )
				{ 
					// Import resource by string.
					const std::string& Name = Resource[ "name" ].asString();
				
					// Check name is a valid length.
					// TODO: Check it only contains valid characters.
					if( Name.length() > 0 )
					{
						// Create a file writer for resource (using full name!)
						CsFile* pFile = createFileWriter( getResourceFullName( Name, Type ) );

						if( pFile != NULL )
						{
							// Add name as first string.
							pFile->addString( Name.c_str() );

							// Allocate resource.
							Handle = allocResource( Name, Type, pFile );
						
							if( Handle.isValid() )
							{							
								// Import the resource immediately (blocking operation).
								if( Handle->import( Resource, *pDependancyList ) )
								{
									BcBool Success = pFile->save();
									BcAssertMsg( Success, "Failed to save out \"%s\"", getResourceFullName( Name, Type ).c_str() );
									if( Success )
									{
										// Now we need to request the resource, this will delete the imported
										// one and replace it with a valid loaded resource.
										internalRequestResource( Name, Type, Handle );
									}
								}	
								else
								{
									// Failed to import, so set handle to NULL to release it.
									Handle = NULL;
								}
							}
							else
							{
								delete pFile;
								BcPrintf( "CsCore: Can not allocate resource type %s.\n", Type.c_str() );
							}
						}
						else
						{
							BcPrintf( "CsCore: Can not allocate file writer.\n" );
						}	
					}
					else
					{
						BcPrintf( "CsCore: Json object does not contain valid name.\n" );
					}
				}
				else
				{
					BcPrintf( "CsCore: Json object does not contain name.\n" );
				}
			}
			else
			{
				BcPrintf( "CsCore: Json object is neither an alias or valid resource.\n" );
			}
		}
		else
		{
			BcPrintf( "CsCore: Json object contains more than 1 element.\n" );
		}
	}
	else
	{
		BcPrintf( "CsCore: Invalid Json object.\n" );		
	}
	return Handle.isValid();
}
Ejemplo n.º 27
0
Json::Value mesos_http::get_task_labels(const std::string& task_id)
{
	std::ostringstream os;
	CURLcode res = get_data(make_uri("/master/tasks"), os);

	Json::Value labels;
	if(res != CURLE_OK)
	{
		g_logger.log(curl_easy_strerror(res), sinsp_logger::SEV_ERROR);
		return labels;
	}

	try
	{
		Json::Value root;
		Json::Reader reader;
		if(reader.parse(os.str(), root, false))
		{
			Json::Value tasks = root["tasks"];
			if(!tasks.isNull())
			{
				for(const auto& task : tasks)
				{
					Json::Value id = task["id"];
					if(!id.isNull() && id.isString() && id.asString() == task_id)
					{
						Json::Value statuses = task["statuses"];
						if(!statuses.isNull())
						{
							double tstamp = 0.0;
							for(const auto& status : statuses)
							{
								// only task with most recent status
								// "TASK_RUNNING" considered
								Json::Value ts = status["timestamp"];
								if(!ts.isNull() && ts.isNumeric() && ts.asDouble() > tstamp)
								{
									Json::Value st = status["state"];
									if(!st.isNull() && st.isString())
									{
										if(st.asString() == "TASK_RUNNING")
										{
											labels = task["labels"];
											tstamp = ts.asDouble();
										}
										else
										{
											labels.clear();
										}
									}
								}
							}
							if(!labels.empty()) // currently running task found
							{
								return labels;
							}
						}
					}
				}
			}
		}
		else
		{
			g_logger.log("Error parsing tasks.\nJSON:\n---\n" + os.str() + "\n---", sinsp_logger::SEV_ERROR);
		}
	}
	catch(std::exception& ex)
	{
		g_logger.log(std::string("Error parsing tasks:") + ex.what(), sinsp_logger::SEV_ERROR);
	}

	return labels;
}
Ejemplo n.º 28
0
// VFALCO ARGH! returning a single std::string for the entire response?
std::string
ServerHandlerImp::processRequest (std::string const& request,
    beast::IP::Endpoint const& remoteIPAddress)
{
    Json::Value jvRequest;
    {
        Json::Reader reader;
        if ((request.size () > 1000000) ||
            ! reader.parse (request, jvRequest) ||
            jvRequest.isNull () ||
            ! jvRequest.isObject ())
        {
            return createResponse (400, "Unable to parse request");
        }
    }

    auto const role = getConfig ().getAdminRole (jvRequest, remoteIPAddress);

    Resource::Consumer usage;

    if (role == Config::ADMIN)
        usage = m_resourceManager.newAdminEndpoint (remoteIPAddress.to_string());
    else
        usage = m_resourceManager.newInboundEndpoint(remoteIPAddress);

    if (usage.disconnect ())
        return createResponse (503, "Server is overloaded");

    // Parse id now so errors from here on will have the id
    //
    // VFALCO NOTE Except that "id" isn't included in the following errors.
    //
    Json::Value const id = jvRequest ["id"];

    Json::Value const method = jvRequest ["method"];

    if (method.isNull ())
        return createResponse (400, "Null method");

    if (! method.isString ())
        return createResponse (400, "method is not string");

    std::string strMethod = method.asString ();
    if (strMethod.empty())
        return createResponse (400, "method is empty");

    // Parse params
    Json::Value params = jvRequest ["params"];

    if (params.isNull ())
        params = Json::Value (Json::arrayValue);

    else if (!params.isArray ())
        return HTTPReply (400, "params unparseable");

    // VFALCO TODO Shouldn't we handle this earlier?
    //
    if (role == Config::FORBID)
    {
        // VFALCO TODO Needs implementing
        // FIXME Needs implementing
        // XXX This needs rate limiting to prevent brute forcing password.
        return HTTPReply (403, "Forbidden");
    }


    std::string response;
    RPCHandler rpcHandler (m_networkOPs);
    Resource::Charge loadType = Resource::feeReferenceRPC;

    m_journal.debug << "Query: " << strMethod << params;

    Json::Value const result (rpcHandler.doRpcCommand (
        strMethod, params, role, loadType));
    m_journal.debug << "Reply: " << result;

    usage.charge (loadType);

    response = JSONRPCReply (result, Json::Value (), id);

    return createResponse (200, response);
}
Ejemplo n.º 29
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;
}
Ejemplo n.º 30
0
Json::Value k8s_state_t::extract_capture_data(const Json::Value& item)
{
	k8s_component::type component = component_from_json(item);

	Json::Value cap_item;

#ifdef HAS_CAPTURE

	Json::Value ver = item["apiVersion"];
	if(!ver.isNull() && ver.isString())
	{
		cap_item["apiVersion"] = ver.asString();
	}
	else
	{
		throw sinsp_exception("K8S capture: API version not provided.");
	}

	Json::Value type = item["type"];
	if(!type.isNull() && type.isString())
	{
		cap_item["type"] = type.asString();
	}
	else
	{
		throw sinsp_exception("K8S capture: event type not provided.");
	}

	Json::Value kind = item["kind"];
	if(!kind.isNull() && kind.isString())
	{
		cap_item["kind"] = kind.asString();
	}
	else
	{
		throw sinsp_exception("K8S capture: component kind not provided.");
	}
	const Json::Value& object = item["object"];
	if(object.isNull())
	{
		throw sinsp_exception("K8S capture: object not found.");
	}

	cap_item["object"] = Json::Value();
	Json::Value& cap_object = cap_item["object"];
	cap_object["metadata"] = Json::Value();
	Json::Value& cap_metadata = cap_object["metadata"];

	const Json::Value& metadata = object["metadata"];
	if(metadata.isNull())
	{
		throw sinsp_exception("K8S capture: object metadata not found.");
	}
	else
	{
		Json::Value ns = metadata["namespace"];
		if(!ns.isNull())
		{
			cap_metadata["namespace"] = ns.asString();
		}
		cap_metadata["name"] = metadata["name"].asString();
		cap_metadata["uid"] = metadata["uid"].asString();

		Json::Value labels = metadata["labels"];
		if(!labels.isNull())
		{
			cap_metadata["labels"] = labels;
		}
	}

	Json::Value spec = object["spec"];
	if(spec.isNull())
	{
		throw sinsp_exception("K8S capture: object spec not found.");
	}
	else
	{
		Json::Value selector = spec["selector"];
		if(!selector.isNull())
		{
			cap_object["spec"] = Json::Value();
			Json::Value& cap_spec = cap_object["spec"];
			cap_spec["selector"] = std::move(selector);
		}
	}

	Json::Value status = object["status"];
	if(status.isNull())
	{
		throw sinsp_exception("K8S capture: object status not found.");
	}

	switch(component)
	{
	case k8s_component::K8S_NAMESPACES:
		break;

	case k8s_component::K8S_NODES:
		{
			cap_object["status"] = Json::Value();
			Json::Value& cap_status = cap_object["status"];
			cap_object["status"] = Json::Value();
			cap_status["addresses"] = status["addresses"];
		}
		break;

	case k8s_component::K8S_PODS:
		{
			cap_object["spec"] = Json::Value();
			Json::Value& cap_spec = cap_object["spec"];
			const Json::Value& node_name = spec["nodeName"];
			if(!node_name.isNull())
			{
				cap_spec["nodeName"] = node_name.asString();
			}

			cap_object["status"] = Json::Value();
			Json::Value& cap_status = cap_object["status"];
			const Json::Value& host_ip = status["hostIP"];
			if(!host_ip.isNull())
			{
				cap_status["hostIP"] = host_ip.asString();
			}
			const Json::Value& pod_ip = status["podIP"];
			if(!pod_ip.isNull())
			{
				cap_status["podIP"] = pod_ip.asString();
			}

			if(status.isMember("containerStatuses") && status["containerStatuses"].isArray())
			{
				for(const auto& c_status : status["containerStatuses"])
				{
					Json::Value new_cid;
					new_cid["containerID"] = c_status["containerID"];
					cap_status["containerStatuses"].append(new_cid);
				}
			}
		}
		break;

	case k8s_component::K8S_SERVICES:
		{
			cap_object["spec"] = Json::Value();
			Json::Value& cap_spec = cap_object["spec"];
			cap_spec["clusterIP"] = spec["clusterIP"].asString();
			cap_spec["ports"] = spec["ports"];
		}
		break;

	case k8s_component::K8S_REPLICATIONCONTROLLERS:
		break;

	default: break;
	}
	std::ostringstream os;
	std::string nspace;
	if(cap_metadata.isMember("namespace"))
	{
		nspace = cap_metadata["namespace"].asString();
	}
	os << "Capture: [" << cap_item["type"].asString() << ',' << cap_item["kind"].asString() << ',' <<
				cap_metadata["name"].asString() << ',' << cap_metadata["uid"].asString() << ',' << nspace << ']';
	g_logger.log(os.str(), sinsp_logger::SEV_DEBUG);
	//g_logger.log(item.toStyledString(), sinsp_logger::SEV_DEBUG);
	//g_logger.log(cap_item.toStyledString(), sinsp_logger::SEV_DEBUG);

#endif // HAS_CAPTURE

	return cap_item;
}