示例#1
0
AccessControlRule::AccessControlRule(const QJsonValueRef &jsonValue) :
	m_name(),
	m_description(),
	m_action( ActionNone ),
	m_parameters(),
	m_invertConditions( false )
{
	if( jsonValue.isObject() )
	{
		QJsonObject json = jsonValue.toObject();

		m_name = json["Name"].toString();
		m_description = json["Description"].toString();
		m_action = static_cast<Action>( json["Action"].toInt() );
		m_invertConditions = json["InvertConditions"].toBool();

		for( auto parametersValue : json["Parameters"].toArray() )
		{
			QJsonObject parametersObj = parametersValue.toObject();
			auto condition = static_cast<Condition>( parametersObj["Condition"].toInt() );

			m_parameters[condition].enabled = parametersObj["Enabled"].toBool();
			m_parameters[condition].subject = static_cast<Subject>( parametersObj["Subject"].toInt() );
			m_parameters[condition].argument = parametersObj["Argument"].toVariant();
		}
	}
}
示例#2
0
RMUser::RMUser(const QJsonValueRef& json, RedMineManager* manager, QObject* parent): 
    QObject(parent),
    m_manager(manager)
{
    assert(json.isObject());
    
    QJsonObject obj = json.toObject();
    
    m_id = obj.value("id").toDouble();
    m_login = obj.value("login").toString();
    m_firstName = obj.value("firstname").toString();
    m_lastName = obj.value("lastname").toString();
    m_email = obj.value("email").toString();
    m_authSourceId = obj.value("auth_source_id").toDouble();
}
示例#3
0
void
FlowViewStyle::
loadJsonFromByteArray(QByteArray const &byteArray)
{
  QJsonDocument json(QJsonDocument::fromJson(byteArray));

  QJsonObject topLevelObject = json.object();

  QJsonValueRef nodeStyleValues = topLevelObject["FlowViewStyle"];

  QJsonObject obj = nodeStyleValues.toObject();

  FLOW_VIEW_STYLE_READ_COLOR(obj, BackgroundColor);
  FLOW_VIEW_STYLE_READ_COLOR(obj, FineGridColor);
  FLOW_VIEW_STYLE_READ_COLOR(obj, CoarseGridColor);
}
示例#4
0
RMProject::RMProject(const QJsonValueRef& json, RedMineManager* manager, QObject* parent): 
    QObject(parent),
    m_manager(manager)
{
    assert(json.isObject());
    
    QJsonObject obj = json.toObject();
    
    m_id = obj.value("id").toDouble();
    m_createdOn = jsonDate(obj.value("created_on").toString());
    m_updatedOn = jsonDate(obj.value("updated_on").toString());
    m_identifier = obj.value("identifier").toString();
    m_name = obj.value("name").toString();
    m_description = obj.value("description").toString();
    
    auto parentProj = obj.value("parent");
    if (parentProj.isObject())
    {
        m_parentProjectId = parentProj.toObject().value("id").toDouble();
    }
}
示例#5
0
void HttpServer::registerRouteFromJSON(QJsonValueRef& obj, HttpMethod method)
{
  if(obj.isArray())
  {
    QJsonArray array = obj.toArray();
    auto item = array.begin();
    while(item != array.end())
    {
      if(item->isObject())
      {
        auto route = item->toObject();
        auto action = route["action"].toString().trimmed();
        auto path = route["path"].toString().trimmed();
        if(route["isActive"] != false && !path.isEmpty())
        {
          this->registerRoute(method, action, path);
        }
      }
      ++item;
    }
  }
}
示例#6
0
int LuaJsonObject::luaIteratorNext( lua_State *L )
{
	JsonObjectUserData			*UserData = (JsonObjectUserData *)lua_touserdata( L, lua_upvalueindex( 1 ) );

	if( UserData->mIterator != UserData->mJsonObject.end() )
	{
		lua_pushfstring( L, "%s", UserData->mIterator.key().toLatin1().constData() );

		QJsonValueRef	 ValRef = *UserData->mIterator;

		switch( ValRef.type() )
		{
			case QJsonValue::Array:
				LuaJsonArray::pushjsonarray( L, ValRef.toArray() );
				break;

			case QJsonValue::Bool:
				lua_pushboolean( L, ValRef.toBool() );
				break;

			case QJsonValue::Double:
				lua_pushnumber( L, ValRef.toDouble() );
				break;

			case QJsonValue::String:
				lua_pushfstring( L, "%s", ValRef.toString().toLatin1().constData() );
				break;

			case QJsonValue::Object:
				LuaJsonObject::pushjsonobject( L, ValRef.toObject() );
				break;

			case QJsonValue::Null:
				lua_pushnil( L );
				break;

			case QJsonValue::Undefined:
				lua_pushnil( L );
				break;
		}

		UserData->mIterator++;

		return( 2 );
	}

	return( 0 );
}
示例#7
0
//---------------------------------------------------------------------------------
Effect::Effect(QJsonValueRef* p_jsonObject, const EffectSource& p_source)
    : _effectType(EFFECTTYPE_INVALID)
    , _source(p_source)
    , _target("")
    , _currentTarget("")
    , _limit("")
{
    QJsonValueRef val = *p_jsonObject;
    QJsonObject obj = val.toObject();
    // Effect type
    QString tempString = obj["type"].toString();
    if (tempString == "increase_skill")
    {
        _effectType = EFFECTTYPE_INCREASE_SKILL;
    }
    else if (tempString == "increase_skill_max")
    {
        // TODO: Mind this when handling skills
        _effectType = EFFECTTYPE_INCREASE_SKILL_MAX;
    }
    else if (tempString == "multiply_skill_category_cost")
    {
        // TODO: Mind this when handling skills
        _effectType = EFFECTTYPE_MULTIPLY_SKILL_CATEGORY_COST;
    }
    else if (tempString == "disable_skill_group")
    {
        // TODO: Mind this when handling skills
        _effectType = EFFECTTYPE_DISABLE_SKILL_GROUP;
    }
    else if (tempString == "allow_skill")
    {
        // TODO: Mind this when enabling skills
        _effectType = EFFECTTYPE_ALLOW_SKILL;
    }
    else if (tempString == "increase_attribute")
    {
        _effectType = EFFECTTYPE_INCREASE_ATTRIBUTE;
    }
    else if (tempString == "increase_attribute_max")
    {
        _effectType = EFFECTTYPE_INCREASE_ATTRIBUTE_MAX;
    }
    else if (tempString == "increase_damage_value")
    {
        // TODO: Mind this when calculating damage values of weapons
        _effectType = EFFECTTYPE_INCREASE_DAMAGE_VALUE;
    }
    else if (tempString == "increase_accuracy")
    {
        // TODO: Mind this when calculating accuracy values of weapons
        _effectType = EFFECTTYPE_INCREASE_ACCURACY;
    }
    else if (tempString == "increase_potential")
    {
        _effectType = EFFECTTYPE_INCREASE_POTENTIAL;
    }
    else if (tempString == "increase_initiative_dice")
    {
        _effectType = EFFECTTYPE_INCREASE_INI_DICE;
    }
    else if (tempString == "increase_armor")
    {
         // TODO: Mind this when calculating armor
        _effectType = EFFECTTYPE_INCREASE_ARMOR;
    }
    else if (tempString == "move_wound_modifier")
    {
         // TODO: Mind this when calculating wound modifiers
        _effectType = EFFECTTYPE_MOVE_WOUND_MODIFIERS;
    }
    else if (tempString == "increase_wound_modifier_section_length")
    {
         // TODO: Mind this when calculating wound modifiers
        _effectType = EFFECTTYPE_INCREASE_WOUND_MODIFIERS_SECTION_LENGTH;
    }
    else if (tempString == "add_free_languages")
    {
         // TODO: Mind this when calculating free languages
        _effectType = EFFECTTYPE_ADD_FREE_LANGUAGES;
    }
    else if (tempString == "increase_memory")
    {
        _effectType = EFFECTTYPE_INCREASE_MEMORY;
    }
    else if (tempString == "increase_notoriety")
    {
        // TODO: Mind this when calculating notoriety
        _effectType = EFFECTTYPE_INCREASE_NOTORIETY;
    }
    else if (tempString == "multiply_cyberware_essence_loss")
    {
        // TODO: Mind this when calculating essence cost of cyberware
        _effectType = EFFECTTYPE_MULTIPLY_CYBERWARE_ESSENCE_LOSS;
    }
    else if (tempString == "disable_bioware")
    {
        // TODO: Mind this when selecting gear
        _effectType = EFFECTTYPE_DISABLE_BIOWARE;
    }
    else if (tempString == "none")
    {
        _effectType = EFFECTTYPE_NONE;
    }

    // Common values
    // Value
    if (obj.contains("value"))
    {
        _value = obj["value"].toString();
    }
    // Limit
    if (obj.contains("limit"))
    {
        _limit = obj["limit"].toString();
    }

    // Type specific values
    // The rather obscure fromUtf16 is used to do a deep copy of the string.
    // If not done, the string will be "garbage collected" or something by Qt itself. Weird.
    // Skills
    if (_effectType == EFFECTTYPE_INCREASE_SKILL ||
        _effectType == EFFECTTYPE_INCREASE_SKILL_MAX ||
        _effectType == EFFECTTYPE_DISABLE_SKILL_GROUP ||
        _effectType == EFFECTTYPE_ALLOW_SKILL ||
        _effectType == EFFECTTYPE_INCREASE_ACCURACY ||
        _effectType == EFFECTTYPE_INCREASE_DAMAGE_VALUE)
    {
        _target = QString::fromUtf16(obj["skill"].toString().utf16());
        _currentTarget = _target;
    }
    // Skill category
    else if (_effectType == EFFECTTYPE_MULTIPLY_SKILL_CATEGORY_COST)
    {
        _target = QString::fromUtf16(obj["category"].toString().utf16());
        _currentTarget = _target;
    }
    // Attributes
    else if (_effectType == EFFECTTYPE_INCREASE_ATTRIBUTE ||
             _effectType == EFFECTTYPE_INCREASE_ATTRIBUTE_MAX)
    {
        _target = QString::fromUtf16(obj["attribute"].toString().utf16());
        _currentTarget = _target;
    }
    // Increase potential
    else if (_effectType == EFFECTTYPE_INCREASE_POTENTIAL)
    {
        _target = QString::fromUtf16(obj["potential"].toString().utf16());
        _currentTarget = _target;
    }
    // Wound modifier movement
    else if (_effectType == EFFECTTYPE_MOVE_WOUND_MODIFIERS ||
             _effectType == EFFECTTYPE_INCREASE_WOUND_MODIFIERS_SECTION_LENGTH)
    {
        _target = QString::fromUtf16(obj["affects"].toString().utf16());
        _currentTarget = _target;
    }

    // Each effect might have multiple conditions
    QJsonArray tempArray;
    if (obj.contains("conditions"))
    {
        tempArray = obj["conditions"].toArray();
        for (int i = 0; i < tempArray.size(); ++i)
        {
            QJsonValueRef valref = tempArray[i];
            _conditions.push_back(new Condition(this, &valref));
        }
    }
}
//! Normalizes property value for use. Receives true if the property value is acceptable for the intended purpose.
bool ObjectVersionCore::normalizePropertyValue( PropertyValuePurpose purpose, QJsonValueRef value )
{
	// Block certain property values.
	QJsonObject asObject = value.toObject();
	switch( purpose )
	{
	case ForDisplay :
		{
			Q_ASSERT( asObject.contains( "PropertyDef" ) );
			int propertyDef = asObject[ "PropertyDef" ].toDouble();
			const int* blocked = qFind( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES,
										BLOCKED_FOR_DISPLAY_PROPERTY_VALUES + sizeof( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES ) / sizeof( int ),
										propertyDef );
			if( blocked != BLOCKED_FOR_DISPLAY_PROPERTY_VALUES + sizeof( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES ) / sizeof( int ) )
				return false;  // The property value was blocked.
		}
		break;

	// All property values are accepted.
	case All:
		break;

	// Unexpected purpose.
	case Undefined :
	default :
		qCritical( "TODO: Error reporting." );
		return false;
		break;
	}

	// Normalize the typed value part.
	QJsonObject typedValue = asObject[ "TypedValue" ].toObject();
	if( ! typedValue.contains( "HasValue" ) )
		typedValue[ "HasValue" ] = false;  // MFWS REST API does not include the field "HasValue" if the value is undefined. This can be considered a bug in MFWS REST API.

	// Perform data type specific normalization.
	Q_ASSERT( typedValue.contains( "DataType" ) );
	int dataType = typedValue[ "DataType" ].toDouble();
	switch( dataType )
	{
	// Single-line text.
	case 1:
		{
			// For single-line text values we explicitly set the value to an empty string
			// if we receive an undefined or null text based value.
			QJsonValue value = typedValue[ "Value" ];
			if( ! typedValue.contains( "Value" ) ||  // "Value" is not included if the value in M-Files is empty/null. This is a bug in MFWS REST API.
				value.isUndefined() || value.isNull() )
			{
				// Ensure that the empty single-line text is represented by a valid string.
				// In M-Files null, undefined and empty string are semantically equivalent.
				typedValue[ "Value" ] = QString( "" );
				typedValue[ "DisplayValue" ] = QString( "" );
			}
		}
		break;

	// Multi-select lookup.
	case 10:
		typedValue[ "DisplayValue" ] = QString();
		break;

	// The data type does not require special handling.
	default:
		break;
	}
	// NOTE: QJsonXYZ objects use implicit sharing of the data. e.g. copies are only created when
	// something is modified. As we just modified the values and created copies we need to assign the copies
	// back to the original values.
	asObject[ "TypedValue" ] = typedValue;  // Re-assign the typed value to the PropertyVAlue object.
	value = asObject;  // Update the actual property value.

	// This property value was accepted.
	return true;
}
/**
 * @brief Sends the given property values to the server. This creates a new version of the object.
 * @param updatedProperties Properties to send.
 */
void ObjectVersionCore::sendPropertiesToServer( const QJsonArray& updatedProperties )
{
	qDebug( "Sending properties to server." );

	// Acquire copy of the current property values.
	QJsonArray forSending;
	{
		QMutexLocker lock( &m_mtx );

		// Check that we actually have valid property values to work with.
		if( m_properties.size() == 0 || m_propertiesForDisplay.size() == 0 )
		{
			qCritical( "TODO: Report error - Must fetch properties before sending them back to the server." );
			return;
		}

		// Take the copy.
		forSending = m_properties;
	}

	// Map update property values by property definition to their location
	// in the input array.
	QHash< int, int > updatedPropertiesIndex;
	for( int i = 0; i < updatedProperties.size(); i++ )
	{
		// Map the current property value by property definition to the index.
		QJsonValue updated = updatedProperties[ i ];
		QJsonObject asObject = updated.toObject();
		int propertyDef = asObject[ "PropertyDef" ].toDouble();
		updatedPropertiesIndex.insert( propertyDef, i );

	}  // end for

	// TODO: Calculate removed properties based on the current for display properties

	// Update the property values with the client provided property values.
	for( QJsonArray::iterator itr = forSending.begin(); itr != forSending.end(); itr++ )
	{
		// Get the property definition of the current property value.
		QJsonValueRef current = (*itr);
		QJsonObject asObject = current.toObject();
		int propertyDef = asObject[ "PropertyDef" ].toDouble();

		// Try finding the property value from the set of updated property values and update it.
		QHash< int, int >::const_iterator itrUpdated = updatedPropertiesIndex.find( propertyDef );
		if( itrUpdated != updatedPropertiesIndex.end() )
		{
			// This property value has been updated.
			qDebug( "Updated property value." );
			current = updatedProperties[ itrUpdated.value() ];
		}

	}  // end for

	// Send the property values to the server.
	QString resource( "/objects/%1/%2/%3/properties?include=properties,propertiesForDisplay" );
	QString args = resource.arg( m_objver.type() ).arg( m_objver.id() ).arg( m_objver.version() );
	QJsonDocument document( forSending );
	QNetworkReply* reply = this->rest()->putJson( args, document );
	QObject::connect( reply, &QNetworkReply::finished,  [=]() {
			this->m_owner->versionAvailable( reply, true ); } );
}
示例#10
0
void HttpServer::initGlobal(const QString &filepath)
{
  LOG_INFO("Processing filepath [" << filepath << "]");

  m_GlobalConfig = Utils::readJson(QDir(filepath).absolutePath());

  LOG_INFO(m_GlobalConfig["bindIp"]);
  LOG_INFO(m_GlobalConfig["bindPort"]);

  QJsonValueRef loggingValue = m_GlobalConfig["logfile"];
  if(loggingValue.isObject())
  {
    QJsonObject logging = loggingValue.toObject();
    if(logging["isEnabled"].toBool(true))
    {
      QString filename;
      if(logging["filename"].isString())
      {
        filename = logging["filename"].toString();
      }
      if(logging["writeFrequency"].isDouble())
      {
        m_LoggingUtils.initializeFile(filename, logging["writeFrequency"].toInt());
      }
      else
      {
        m_LoggingUtils.initializeFile(filename);
      }
    }
  }

  QJsonValueRef httpFilesValue = m_GlobalConfig["httpFiles"];
  if(httpFilesValue.isObject())
  {
    QJsonObject httpFiles = httpFilesValue.toObject();
    m_ShouldServeFiles = httpFiles["isEnabled"].toBool(false);
    if(m_ShouldServeFiles)
    {
      QString directory = httpFiles["directory"].toString().trimmed();
      if(directory == "$QTTP_HOME")
      {
        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        if(env.contains(QTTP_HOME_ENV_VAR))
        {
          m_ServeFilesDirectory = QDir::cleanPath(env.value(QTTP_HOME_ENV_VAR));
          m_ServeFilesDirectory = m_ServeFilesDirectory.absoluteFilePath("www");
          LOG_DEBUG("Using $QTTP_HOME" << m_ServeFilesDirectory.absolutePath());
        }
        else
        {
          m_ServeFilesDirectory = QDir::current().absoluteFilePath("www");
          LOG_DEBUG("QTTP_HOME not found, using current directory" << m_ServeFilesDirectory.absolutePath());
        }
      }
      else if(directory.isEmpty())
      {
        m_ServeFilesDirectory = QDir::current().absoluteFilePath("www");
        LOG_DEBUG("Default to using current directory" << m_ServeFilesDirectory.absolutePath());
      }
      else
      {
        m_ServeFilesDirectory = QDir::cleanPath(directory);
        LOG_DEBUG("Using directory in config" << m_ServeFilesDirectory.absolutePath());
      }
      if(!m_ServeFilesDirectory.exists())
      {
        LOG_ERROR("Unable to serve files from invalid directory [" << m_ServeFilesDirectory.absolutePath() << "]");
        m_ShouldServeFiles = false;
      }
    }
  }

  if(m_ShouldServeFiles)
  {
    m_FileLookup.populateFiles(m_ServeFilesDirectory);
  }

  QJsonObject headers = m_GlobalConfig["defaultHeaders"].toObject();
  QStringList keys = headers.keys();

  if(!keys.isEmpty())
  {
    Global::DEFAULT_HEADERS.clear();
    for(QString key : keys)
    {
      QString value = headers.value(key).toString();
      Global::DEFAULT_HEADERS.push_back({ key, value });
      LOG_DEBUG("Adding default-header [" << key << ", " << value << "]");
    }

    // We'll always force the QttpServer version in here.
    Global::DEFAULT_HEADERS.push_back({ "Server", QTTP_SERVER_VERSION });
  }
  else
  {
    LOG_DEBUG("Did not read headers in config file, using default headers");
  }

  QJsonObject serverConfig = m_GlobalConfig["server"].toObject();
  m_SendRequestMetadata = serverConfig["metadata"].toBool(false);
  m_StrictHttpMethod = serverConfig["strictHttpMethod"].toBool(false);

  QJsonObject processors = serverConfig["processors"].toObject();
  keys = processors.keys();
  for(QString key : keys)
  {
    bool isEnabled = processors.value(key).toBool(false);

    LOG_DEBUG("Processor [" << key << "] is " <<
              (isEnabled ? "ENABLED" : "NOT ENABLED"));

    if(isEnabled)
    {
      m_EnabledProcessors.append(key);
    }
  }

  QJsonObject swagger = m_GlobalConfig["swagger"].toObject();
  initSwagger(swagger["isEnabled"].toBool(false));

#ifndef ASSIGN_SWAGGER
#  define ASSIGN_SWAGER(X) m_ServerInfo.X = swagger[#X].toString()
#endif

  ASSIGN_SWAGER(host);
  ASSIGN_SWAGER(basePath);
  ASSIGN_SWAGER(version);
  ASSIGN_SWAGER(title);
  ASSIGN_SWAGER(description);
  ASSIGN_SWAGER(termsOfService);

  QJsonObject company = swagger["company"].toObject();
  m_ServerInfo.companyName = company["name"].toString();
  m_ServerInfo.companyUrl = company["url"].toString();

  QJsonObject contact = swagger["contact"].toObject();
  m_ServerInfo.contactEmail = contact["email"].toString();

  QJsonObject license = swagger["license"].toObject();
  m_ServerInfo.licenseName = license["name"].toString();
  m_ServerInfo.licenseUrl = license["url"].toString();

  m_ServerInfo.schemes = swagger["schemes"].toArray();
  m_ServerInfo.consumes = swagger["consumes"].toArray();
  m_ServerInfo.produces = swagger["produces"].toArray();
}
示例#11
0
//Чисто парсим JSon файл. Раскидываем по полочкам
void getTable::parser()
{
    QJsonDocument d = QJsonDocument::fromJson(httpResponse.toUtf8());//
    QJsonObject jsonObj = d.object();

    for(QJsonObject::iterator it = jsonObj.begin(); it != jsonObj.end(); it++)
    {
        QJsonValueRef tmp = (it.value());
        QJsonObject CJson = tmp.toObject();
        QJsonObject::iterator cell = CJson.begin();

        if(it == jsonObj.begin()){
            ui->car_00->setNum(cell.value().toDouble());
            cell++;
            ui->human_00->setNum(cell.value().toDouble());
            cell++;
            ui->success_00->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 1){
            ui->car_03->setNum(cell.value().toDouble());
            cell++;
            ui->human_03->setNum(cell.value().toDouble());
            cell++;
            ui->success_03->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 2){
            ui->car_06->setNum(cell.value().toDouble());
            cell++;
            ui->human_06->setNum(cell.value().toDouble());
            cell++;
            ui->success_06->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 3){
            ui->car_09->setNum(cell.value().toDouble());
            cell++;
            ui->human_09->setNum(cell.value().toDouble());
            cell++;
            ui->success_09->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 4){
            ui->car_12->setNum(cell.value().toDouble());
            cell++;
            ui->human_12->setNum(cell.value().toDouble());
            cell++;
            ui->success_12->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 5){
            ui->car_15->setNum(cell.value().toDouble());
            cell++;
            ui->human_15->setNum(cell.value().toDouble());
            cell++;
            ui->success_15->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 6){
            ui->car_18->setNum(cell.value().toDouble());
            cell++;
            ui->human_18->setNum(cell.value().toDouble());
            cell++;
            ui->success_18->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 7){
            ui->car_21->setNum(cell.value().toDouble());
            cell++;
            ui->human_21->setNum(cell.value().toDouble());
            cell++;
            ui->success_21->setNum(cell.value().toDouble());
        }
    }
}