Example #1
0
void WString::ReadFromStream(size_t (*streamReader)(wchar_t *buffer, size_t bufferLen, void *context),void *context)
{
  _ref->Release();
  _ref = NULL;
  wchar_t buff[256];
  size_t rd;
  while ((rd = streamReader(buff,sizeof(buff)/sizeof(wchar_t),context)) != 0)
  {
	*this = *this+WString(buff,rd);
  }
}
void SvCreator::handleImportNagiosBPIConfigAsBusinessView(void)
{
  QMap<QString, SourceT> sourceInfos;
  fetchSourceList(MonitorT::Nagios, sourceInfos);
  CheckImportationSettingsForm importationSettingForm(sourceInfos.keys(), true);
  if (importationSettingForm.exec() != QDialog::Accepted) {
    return;
  }


  QFile file(importationSettingForm.selectedFile());
  if (! file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    showStatusMsg(tr("Cannot open file: %1").arg(importationSettingForm.selectedFile()), true);
    return;
  }

  QString sourceId = importationSettingForm.selectedSource();

  bool parsingFailed = false;
  QString line;
  int lineIndex = 0;
  QTextStream streamReader(&file);
  NodeT rootService;
  rootService.id = ngrt4n::ROOT_ID;
  rootService.name = tr("Nagios BPI Services");

  ngrt4n::clearCoreData(m_cdata);
  while (line = streamReader.readLine(), ! line.isNull()) {

    ++lineIndex;

    line = line.trimmed();
    if ( line.startsWith("#")
         || line.isEmpty()
         || ! line.startsWith("define")) continue;

    if (! line.endsWith("{")) {
      showStatusMsg(tr("Group definition must end with '{' at line %1").arg(QString::number(lineIndex)), true);
      parsingFailed = true;
      break;
    }

    QStringList fields = line.mid(0, line.size() - 1).trimmed().split(" ");
    if (fields.size() != 2) {
      showStatusMsg(tr("Bad group definition at line %1").arg(QString::number(lineIndex)), true);
      parsingFailed = true;
      break;
    }

    QString groudId = fields[1];

    NodeListT::Iterator currentNode = m_cdata.bpnodes.find(groudId);
    if (currentNode == m_cdata.bpnodes.end()) {
      currentNode = m_cdata.bpnodes.insert(groudId, createNode(groudId, "", ""));
    }

    currentNode->sev_crule = CalcRules::Worst;

    // now parse group config
    int groupMembersCount = 0;
    float warningThreshold  = 0;
    float criticalThreshold = 0;
    while (line = streamReader.readLine(), ! line.isNull()) {

      ++lineIndex;

      line = line.trimmed();

      if (line.isEmpty()) continue;
      if (line == "}") break;

      fields = line.split("=");
      if (fields.size() != 2) {
        showStatusMsg(tr("Bad group attribute definition at line %1").arg(QString::number(lineIndex)), true);
        parsingFailed = true;
        break;
      }

      if (fields[0] == "title") {
        currentNode->name = fields[1];
      } else if (fields[0] == "desc") {
        currentNode->description = fields[1];
      } else if (fields[0] == "members") {
        bool hasCluster = false;
        QString members = fields[1];
        groupMembersCount = extractNagiosBPIGroupMembers(currentNode->id, sourceId, members,
                                                         m_cdata.bpnodes, m_cdata.cnodes, currentNode->child_nodes,
                                                         hasCluster);
        if (groupMembersCount < 0) {
          parsingFailed = true;
          break;
        } else {
          currentNode->sev_crule = hasCluster ? CalcRules::Average : CalcRules::Worst;
        }

      } else if (fields[0] == "warning_threshold") {
        warningThreshold = fields[1].toFloat();
      } else if (fields[0] == "critical_threshold") {
        criticalThreshold = fields[1].toFloat();
      } else if (fields[0] == "priority") {
        /// not applicable
      }
    }


    if (parsingFailed) {
      break;
    } else {
      if (groupMembersCount > 0) {
        if (warningThreshold > 0 || criticalThreshold > 0) {
          currentNode->sev_crule = CalcRules::WeightedAverageWithThresholds;
        }
        if (warningThreshold > 0.0) {
          currentNode->thresholdLimits.push_back({warningThreshold / groupMembersCount, ngrt4n::Major, ngrt4n::Major});
        }
        if (warningThreshold > 0.0 ) {
          currentNode->thresholdLimits.push_back({criticalThreshold / groupMembersCount, ngrt4n::Critical, ngrt4n::Critical});
        }
      }
    }
  }

  if (parsingFailed) {
    ngrt4n::clearCoreData(m_cdata);
  } else {
    attachOrphanedNodesToRoot(m_cdata.bpnodes, rootService);
    attachOrphanedNodesToRoot(m_cdata.cnodes, rootService);
    m_cdata.bpnodes.insert(rootService.id, rootService);
  }
  file.close();
  refreshUIWidgets();
}
    //
    // Loads the profile from the WININET cache
    //
    bool SourceDynamicProfileManager::LoadFromProfileCache(IActiveScriptDataCache* profileDataCache, LPCWSTR url)
    {
    #ifdef ENABLE_WININET_PROFILE_DATA_CACHE
        AssertMsg(CONFIG_FLAG(WininetProfileCache), "Profile caching should be enabled for us to get here");
        Assert(profileDataCache);
        AssertMsg(!IsProfileLoadedFromWinInet(), "Duplicate profile cache loading?");

        // Keep a copy of this and addref it
        profileDataCache->AddRef();
        this->profileDataCache = profileDataCache;

        IStream* readStream;
        HRESULT hr = profileDataCache->GetReadDataStream(&readStream);
        if(SUCCEEDED(hr))
        {
            Assert(readStream != nullptr);
            // stream reader owns the stream and will close it on destruction
            SimpleStreamReader streamReader(readStream);
            DWORD jscriptMajorVersion;
            DWORD jscriptMinorVersion;
            if(FAILED(AutoSystemInfo::GetJscriptFileVersion(&jscriptMajorVersion, &jscriptMinorVersion)))
            {
                return false;
            }

            DWORD majorVersion;
            if(!streamReader.Read(&majorVersion) || majorVersion != jscriptMajorVersion)
            {
                return false;
            }

            DWORD minorVersion;
            if(!streamReader.Read(&minorVersion) || minorVersion != jscriptMinorVersion)
            {
                return false;
            }

            uint numberOfFunctions;
            if(!streamReader.Read(&numberOfFunctions) || numberOfFunctions > MAX_FUNCTION_COUNT)
            {
                return false;
            }
            BVFixed* functions = BVFixed::New(numberOfFunctions, this->recycler);
            if(!streamReader.ReadArray(functions->GetData(), functions->WordCount()))
            {
                return false;
            }
            this->cachedStartupFunctions = functions;
            OUTPUT_TRACE(Js::DynamicProfilePhase, L"Profile load succeeded. Function count: %d  %s\n", numberOfFunctions, url);
#if DBG_DUMP
            if(PHASE_TRACE1(Js::DynamicProfilePhase) && Js::Configuration::Global.flags.Verbose)
            {
                OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, L"Profile loaded:\n");
                functions->Dump();
            }
#endif
            return true;
        }
        else if (hr == HRESULT_FROM_WIN32(ERROR_WRITE_PROTECT))
        {
            this->isNonCachableScript = true;
            OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, L"Profile load failed. Non-cacheable resource. %s\n", url);
        }
        else
        {
            OUTPUT_TRACE(Js::DynamicProfilePhase, L"Profile load failed. No read stream. %s\n", url);
        }
#endif
        return false;
    }
Example #4
0
void Mesh::transform()
{
	const NifModel * nif = static_cast<const NifModel *>( iBlock.model() );
	if ( ! nif || ! iBlock.isValid() )
	{
		clear();
		return;
	}
	
	if ( upData )
	{
		upData = false;
		
		// update for NiMesh
		if ( nif->checkVersion( 0x14050000, 0 ) && nif->inherits( iBlock, "NiMesh" ) )
		{
#ifndef QT_NO_DEBUG
			// do stuff
			qWarning() << "Entering NiMesh decoding...";
			// mesh primitive type
			QString meshPrimitiveType = NifValue::enumOptionName( "MeshPrimitiveType", nif->get<uint>( iData, "Primitive Type" ) );
			qWarning() << "Mesh uses" << meshPrimitiveType;
			for ( int i = 0; i < nif->rowCount( iData ); i ++ )
			{
				// each data reference is to a single data stream
				quint32 stream = nif->getLink( iData.child( i, 0 ), "Stream" );
				qWarning() << "Data stream: " << stream;
				// can have multiple submeshes, unsure of exact meaning
				ushort numSubmeshes = nif->get<ushort>( iData.child( i, 0 ), "Num Submeshes" );
				qWarning() << "Submeshes: " << numSubmeshes;
				QPersistentModelIndex submeshMap = nif->getIndex( iData.child( i, 0 ), "Submesh To Region Map" );
				for ( int j = 0; j < numSubmeshes; j++ )
				{
					qWarning() << "Submesh" << j << "maps to region" << nif->get<ushort>( submeshMap.child( j, 0 ) );
				}
				// each stream can have multiple components, and each has a starting index
				QMap<uint, QString> componentIndexMap;
				int numComponents = nif->get<int>( iData.child( i, 0 ), "Num Components" );
				qWarning() << "Components: " << numComponents;
				// semantics determine the usage
				QPersistentModelIndex componentSemantics = nif->getIndex( iData.child( i, 0 ), "Component Semantics" );
				for( int j = 0; j < numComponents; j++ )
				{
					QString name = nif->get<QString>( componentSemantics.child( j, 0 ), "Name" );
					uint index = nif->get<uint>( componentSemantics.child( j, 0 ), "Index" );
					qWarning() << "Component" << name << "at position" << index << "of component" << j << "in stream" << stream;
					componentIndexMap.insert( j, QString( "%1 %2").arg( name ).arg( index ) );
				}
				
				// now the data stream itself...
				QPersistentModelIndex dataStream = nif->getBlock( stream );
				QByteArray streamData = nif->get<QByteArray>( nif->getIndex( dataStream, "Data" ).child( 0, 0 ) );
				QBuffer streamBuffer( &streamData );
				streamBuffer.open( QIODevice::ReadOnly );
				// probably won't use this
				QDataStream streamReader( &streamData, QIODevice::ReadOnly );
				// we should probably check the header here, but we expect things to be little endian
				streamReader.setByteOrder( QDataStream::LittleEndian );
				// each region exists within the data stream at the specified index
				quint32 numRegions = nif->get<quint32>( dataStream, "Num Regions");
				QPersistentModelIndex regions = nif->getIndex( dataStream, "Regions" );
				quint32 totalIndices = 0;
				if ( regions.isValid() )
				{
					qWarning() << numRegions << " regions in this stream";
					for( quint32 j = 0; j < numRegions; j++ )
					{
						qWarning() << "Start index: " << nif->get<quint32>( regions.child( j, 0 ), "Start Index" );
						qWarning() << "Num indices: " << nif->get<quint32>( regions.child( j, 0 ), "Num Indices" );
						totalIndices += nif->get<quint32>( regions.child( j, 0 ), "Num Indices" );
					}
					qWarning() << totalIndices << "total indices in" << numRegions << "regions";
				}
				uint numStreamComponents = nif->get<uint>( dataStream, "Num Components" );
				qWarning() << "Stream has" << numStreamComponents << "components";
				QPersistentModelIndex streamComponents = nif->getIndex( dataStream, "Component Formats" );
				// stream components are interleaved, so we need to know their type before we read them
				QList<uint> typeList;
				for( uint j = 0; j < numStreamComponents; j++ )
				{
					uint compFormat = nif->get<uint>( streamComponents.child( j, 0 ) );
					QString compName = NifValue::enumOptionName( "ComponentFormat", compFormat );
					qWarning() << "Component format is" << compName;
					qWarning() << "Stored as a" << compName.split( "_" )[1];
					typeList.append( compFormat - 1 );
					
					// this can probably wait until we're reading the stream values
					QString compNameIndex = componentIndexMap.value( j );
					QString compType = compNameIndex.split( " " )[0];
					uint startIndex = compNameIndex.split( " " )[1].toUInt();
					qWarning() << "Component" << j << "contains" << compType << "starting at index" << startIndex;

					// try and sort out texcoords here...
					if( compType == "TEXCOORD" )
					{
						QVector<Vector2> tempCoords;
						coords.append( tempCoords );
						qWarning() << "Assigning coordinate set" << startIndex;
					}

				}	
				
				// for each component
				// get the length
				// get the underlying type (will probably need OpenEXR to deal with float16 types)
				// read that type in, k times, where k is the length of the vector
				// start index will not be 0 if eg. multiple UV maps, but hopefully we don't have multiple components
				
				for( uint j = 0; j < totalIndices; j++ )
				{
					for( uint k = 0; k < numStreamComponents; k++ )
					{
						int typeLength = ( ( typeList[k] & 0x000F0000 ) >> 0x10 );
						int typeSize = ( ( typeList[k] & 0x00000F00 ) >> 0x08 );
						qWarning() << "Reading" << typeLength << "values" << typeSize << "bytes";

						NifIStream tempInput( new NifModel, &streamBuffer );
						QList<NifValue> values;
						NifValue tempValue;
						// if we had the right types, we could read in Vector etc. and not have the mess below
						switch( ( typeList[k] & 0x00000FF0 ) >> 0x04 )
						{
							case 0x10:
								tempValue.changeType( NifValue::tByte );
								break;
							case 0x21:
								tempValue.changeType( NifValue::tShort );
								break;
							case 0x42:
								tempValue.changeType( NifValue::tInt );
								break;
							case 0x43:
								tempValue.changeType( NifValue::tFloat );
								break;
						}
						for( int l = 0; l < typeLength; l++ )
						{
							tempInput.read( tempValue );
							values.append( tempValue );
							qWarning() << tempValue.toString();
						}
						QString compType = componentIndexMap.value( k ).split( " " )[0];
						qWarning() << "Will store this value in" << compType;
						// the mess begins...
						if( NifValue::enumOptionName( "ComponentFormat", (typeList[k] + 1 ) ) == "F_FLOAT32_3" )
						{
							Vector3 tempVect3( values[0].toFloat(), values[1].toFloat(), values[2].toFloat() );
							if( compType == "POSITION" )
							{
								verts.append( tempVect3 );
							}
							else if( compType == "NORMAL" )
							{
								norms.append( tempVect3 );
							}
						}
						else if( compType == "INDEX" )
						{
							indices.append( values[0].toCount() );
						}
						else if( compType == "TEXCOORD" )
						{
							Vector2 tempVect2( values[0].toFloat(), values[1].toFloat() );
							quint32 coordSet = componentIndexMap.value( k ).split( " " )[1].toUInt();
							qWarning() << "Need to append" << tempVect2 << "to texcoords" << coordSet;
							QVector<Vector2> currentSet = coords[coordSet];
							currentSet.append( tempVect2 );
							coords[coordSet] = currentSet;
						}
					}
				}

				// build triangles, strips etc.
				if( meshPrimitiveType == "MESH_PRIMITIVE_TRIANGLES" )
				{
					for( int k = 0; k < indices.size(); )
					{
						Triangle tempTri( indices[k], indices[k+1], indices[k+2] );
						qWarning() << "Inserting triangle" << tempTri;
						triangles.append( tempTri );
						k = k+3;
					}
				}
			}
#endif
		}
		else
		{