Esempio n. 1
0
/**
 * Prepares SignedInfo
 *
 * @param signer signer that signs the signature object.
 * @throws SignatureException exception is throws if signing failed.
 */
std::vector<unsigned char> digidoc::SignatureBES::prepareSignedInfo(Signer* signer) throw(SignatureException, SignException)
{
    // Calculate digests for the documents and add these to the signature reference.
    for(unsigned int i = 0; i < bdoc.documentCount(); ++i)
    {
        digidoc::Document doc = bdoc.getDocument(i);
        try
        {
            DEBUG("Adding document '%s', '%s' to the signature references.", doc.getFileName().c_str(), doc.getMediaType().c_str());
            // URIs must encode non-ASCII characters in the format %HH where HH is the hex representation of the character
            std::string uri = std::string("/") + digidoc::util::File::toUri(doc.getFileName());
            std::auto_ptr<Digest> calc(new Digest());
            std::vector<unsigned char> digest = doc.calcDigest(calc.get());
            DEBUGMEM("digest", &digest[0], digest.size());
            addReference(uri, calc->getUri(), digest);
        }
        catch(const Exception& e)
        {
            delete signature;
            THROW_SIGNEXCEPTION_CAUSE(e, "Failed to calculate digests for document '%s'.", doc.getFileName().c_str());
        }
    }

    // Set required signature fields.
    try
    {
        setSigningCertificate(signer->getCert());
        setSignatureProductionPlace(signer->getSignatureProductionPlace());
        setSignerRole(signer->getSignerRole());
        setSigningTime(util::date::currentTime());
    }
    catch( const IOException &e )
    {
        THROW_SIGNEXCEPTION_CAUSE( e, "Failed to sign document" );
    }

    xml_schema::Uri uri(URI_ID_RSA_SHA1);
    switch(signer->type())
    {
    case NID_sha224: uri = xml_schema::Uri(URI_ID_RSA_SHA224); break;
    case NID_sha256: uri = xml_schema::Uri(URI_ID_RSA_SHA256); break;
    case NID_sha384: uri = xml_schema::Uri(URI_ID_RSA_SHA384); break;
    case NID_sha512: uri = xml_schema::Uri(URI_ID_RSA_SHA512); break;
    default: break;
    }
    signature->signedInfo().signatureMethod(dsig::SignatureMethodType(uri));

    // Calculate digest of the Signature->Object->SignedProperties node.
    std::auto_ptr<Digest> calc(new Digest());
    std::vector<unsigned char> digest = calcDigestOnNode(calc.get(), XADES_NAMESPACE, "SignedProperties");
    addReference("#" + getId() +"-SignedProperties", calc->getUri(), digest, "http://uri.etsi.org/01903#SignedProperties");

    // Calculate SHA digest of the Signature->SignedInfo node.
    calc.reset(new Digest(signer->type()));
    return calcDigestOnNode(calc.get(), URI_ID_DSIG, "SignedInfo");
}
Esempio n. 2
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,Pixmap pixmap_,
		      int w_,int h_,int depth_,unsigned long fg_,unsigned long bg_)
{
  _pData=new MSPixmapData(pServer_,pName_,pixmap_,w_,h_,depth_,fg_,bg_);
  addToHashTable(pName_,(void *)_pData);
  addReference();
}
Esempio n. 3
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,const char *bitmapFile_)
{
  Display *display=pServer_->display();
  Window window=pServer_->root();
  unsigned w,h;
  Pixmap bitmap;
  if (XReadBitmapFile(display,window,bitmapFile_,&w,&h,&bitmap,0,0)==BitmapSuccess)
   {
     _pData=new MSPixmapData(pServer_,pName_,bitmap,bitmap,w,h,1,0,0);
     addToHashTable(pName_,(void *)_pData);
     addReference();     
   }
  else
   {
     // Can't read bitmap file, create one with background color
     MSMessageLog::warningMessage("MSPixmap warning: Unable to create Pixmap from file `%s'\n",
				  bitmapFile_);
     char buf[255];
     unsigned long fg=pServer_->defaultForeground();
     unsigned long bg=pServer_->defaultBackground();
     int depth=DefaultDepthOfScreen(pServer_->screen());
     sprintf(buf,"Predefined_%s_%d_%d_%d_%d",MSPixmap::SolidBackgroundPixmap,fg,bg,depth,display);
     if(copyPixmapDataWithKey(buf)==MSFalse) 
       create(pServer_,MSPixmap::SolidBackgroundPixmap,fg,bg);
   }
}
Esempio n. 4
0
/**
 * Sign the signature using BDOC-BES profile. Sets required fields,
 * calculates digests and finally signs the signature object using
 * the provided <code>signer</code> implementation.
 *
 * @param signer signer that signs the signature object.
 * @throws SignatureException exception is throws if signing failed.
 */
void digidoc::SignatureBES::sign(Signer* signer) throw(SignatureException, SignException)
{
    // Set required signature fields.
    try
    {
        setSigningCertificate(signer->getCert());
        setSignatureProductionPlace(signer->getSignatureProductionPlace());
        setSignerRole(signer->getSignerRole());
        setSigningTime(util::date::currentTime());
    }
    catch( const IOException &e )
    {
        THROW_SIGNEXCEPTION_CAUSE( e, "Failed to sign document" );
    }

    // Calculate digest of the Signature->Object->SignedProperties node.
    std::auto_ptr<Digest> calc = Digest::create();
    std::vector<unsigned char> digest = calcDigestOnNode(calc.get(), XADES_NAMESPACE, "SignedProperties");
    addReference("#S0-SignedProperties", calc->getUri(), digest, "http://uri.etsi.org/01903#SignedProperties");

    // Calculate SHA1 digest of the Signature->SignedInfo node.
    calc = Digest::create(NID_sha1);
    std::vector<unsigned char> sha1 = calcDigestOnNode(calc.get(), DSIG_NAMESPACE, "SignedInfo");
    Signer::Digest sigDigestSha1 = { NID_sha1, &sha1[0], calc->getSize() };

    // Sign the calculated SAH1 digest and add the signature value (SHA1-RSA) to the signature.
    std::vector<unsigned char> buf(128);
    Signer::Signature signatureSha1Rsa = { &buf[0], buf.size() };
    signer->sign(sigDigestSha1, signatureSha1Rsa);
    setSignatureValue(signatureSha1Rsa);
}
Esempio n. 5
0
        void ModelForeignKey::init(Model* model, int id){
            deleteReference();
            mModel=model;
            mId=id;

            addReference();
        }
Esempio n. 6
0
 bool ModelForeignKey::setId(int id){
     if(mModel==NULL){
         return false;
     }
     deleteReference();
     mId=id;
     addReference();
     return true;
 }
void Reader::insertToken(TokenDaemon *tokend)
{
	RefPointer<Token> token = new Token();
	token->insert(*this, tokend);
	mToken = token;
	addReference(*token);
	secdebug("reader", "%p (%s) inserted token %p",
		this, name().c_str(), mToken);
}
Esempio n. 8
0
void BaseTagHDF5::references(const std::vector<DataArray> &refs_new) {
    while (referenceCount() > 0) {
        removeReference(getReference(0)->id());
    }

    for (const auto &ref : refs_new) {
        addReference(ref.id());
    }
}
Esempio n. 9
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,const char *bitmap_,
		      int w_,int h_)
{
  Pixmap pixmap=XCreateBitmapFromData(pServer_->display(),pServer_->root(),(char*)bitmap_,
                                      w_,h_);
  _pData=new MSPixmapData(pServer_,pName_,pixmap,pixmap,w_,h_,1,0,0);
  addToHashTable(pName_,(void *)_pData);
  addReference();  
}
/**
	Writes a 'references' node containing the different bibliographic references of
	the given article.
	@param references: vector with the ids of the articles referenced by the article to add
*/
void ExtendedArticlesXMLGenerator::addReferences(const vector<int> &references)
{
	addOpenningTag(aXMLFile, "references");
	uint nRefs=references.size();
	for(uint i=0; i<nRefs; i++){
		addReference(references[i]);
	}
	addClosingTag(aXMLFile, "references");
}
Esempio n. 11
0
gep::CollisionMesh* gep::CollisionMeshFileLoader::loadResource(CollisionMesh* pInPlace)
{
    CollisionMesh* result = nullptr;
    bool isInPlace = true;
    if (pInPlace == nullptr)
    {
        result = new CollisionMesh();
        isInPlace = false;
    }
    auto* havokLoader = g_resourceManager.getHavokResourceLoader();
    auto* container = havokLoader->load(m_path.c_str());
    GEP_ASSERT(container != nullptr, "Could not load asset! %s", m_path.c_str());

    if (container)
    {
        auto* physicsData = reinterpret_cast<hkpPhysicsData*>(container->findObjectByType(hkpPhysicsDataClass.getName()));
        GEP_ASSERT(physicsData != nullptr, "Unable to load physics data!");

        if (physicsData)
        {
            const auto& physicsSystems = physicsData->getPhysicsSystems();
            GEP_ASSERT(physicsSystems.getSize() == 1, "Wrong number of physics systems!");
            auto body = physicsSystems[0]->getRigidBodies()[0];
            auto hkShape = body->getCollidable()->getShape();

            auto shape = conversion::hk::from(const_cast<hkpShape*>(hkShape));

            auto type = shape->getShapeType();
            if ( type == hkcdShapeType::BV_COMPRESSED_MESH ||
                 type == hkcdShapeType::CONVEX_VERTICES )
            {
                hkTransform transform = body->getTransform();
                transform.getRotation().setAxisAngle(hkVector4(0.0f, 0.0f, 1.0f), GetPi<float>::value());

                auto hkTransformShape = new hkpTransformShape(hkShape, transform);
                hkTransformShape->addReference();
                shape = GEP_NEW(m_pAllocator, HavokShape_Transform)(hkTransformShape);
                //auto meshShape = static_cast<HavokMeshShape*>(shape);
                //Transform* tempTrans = new Transform();
                //conversion::hk::from(transform, *tempTrans);
                //
                //// Since havok content tools are buggy (?) and no custom transformation can be applied,
                //// we have to convert into our engine's space by hand.
                //// TODO: Ensure, that this transformation is correct in every case
                //tempTrans->setRotation(tempTrans->getRotation() * Quaternion(vec3(1,0,0),180));
                //meshShape->setTransform(tempTrans);
            }


            result->setShape(shape);
            
        }

    }
    return result;
}
Esempio n. 12
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,const char *bitmap_,
		      int w_,int h_,unsigned long fg_,unsigned long bg_)
{
  int dep=DefaultDepthOfScreen(pServer_->screen());
  Pixmap p=XCreatePixmapFromBitmapData(pServer_->display(),pServer_->root(),(char*)bitmap_,
				       w_,h_,fg_,bg_,dep);
  _pData=new MSPixmapData(pServer_,pName_,p,w_,h_,dep,fg_,bg_);
  addToHashTable(pName_,(void *)_pData);
  addReference();  
}
Esempio n. 13
0
    void start ()
    {
        assert (m_stopped == true);
        assert (m_stop_called == false);

        if (m_stopped.exchange (false) == true)
        {
            m_stop_complete.reset ();
            addReference ();
        }
    }
Esempio n. 14
0
 NameResolverImpl (boost::asio::io_service& io_service,
     Journal journal)
         : m_journal (journal)
         , m_io_service (io_service)
         , m_strand (io_service)
         , m_resolver (io_service)
         , m_called_stop (0)
         , m_stopped (false)
         , m_idle (true)
         , m_event (true)
 {
     addReference ();
 }
Esempio n. 15
0
    void start () override
    {
        assert (m_stopped == true);
        assert (m_stop_called == false);

        if (m_stopped.exchange (false) == true)
        {
            {
                std::lock_guard<std::mutex> lk{m_mut};
                m_asyncHandlersCompleted = false;
            }
            addReference ();
        }
    }
Esempio n. 16
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,
		      const char *bitmapFile_,unsigned long fg_,unsigned long bg_)
{
  Display *display=pServer_->display();
  Window window=pServer_->root();
  int depth=DefaultDepthOfScreen(pServer_->screen());
  unsigned w,h;
  Pixmap bitmap;
#ifdef MS_WINDOWS
  int res;
  if (bitmapFile_==0) res=MSXReadBitmapFromResource(display,window,_name,&w,&h,&bitmap);
  else res=MSXReadBitmapFromXbmFile(display,window,bitmapFile_,&w,&h,&bitmap,fg_,bg_,depth);
  if( res==BitmapSuccess)
  {
     _pData=new MSPixmapData(pServer_,pName_,bitmap,w,h,depth,fg_,bg_);

#else
  if (XReadBitmapFile(display,window,bitmapFile_,&w,&h,&bitmap,0,0)==BitmapSuccess)
   {
     Pixmap pixmap=XCreatePixmap(display,window,w,h,depth);
     GC gc=XCreateGC(display,window,0,0);
     XSetForeground(display,gc,fg_);
     XSetBackground(display,gc,bg_);
     XCopyPlane(display,bitmap,pixmap,gc,0,0,w,h,0,0,1);
     XFreeGC(display,gc);
     XFreePixmap(display,bitmap);
     _pData=new MSPixmapData(pServer_,pName_,pixmap,w,h,depth,fg_,bg_);
#endif
     addToHashTable(pName_,(void *)_pData);
     addReference();     
   }
  else
   {
     // Can't read bitmap file, create one with background color
     MSMessageLog::warningMessage("MSPixmap warning: Unable to create Pixmap from file %s\n",bitmapFile_);
     char buf[255];
     sprintf(buf,"Predefined_%s_%d_%d_%d_%d",MSPixmap::SolidBackgroundPixmap,fg_,bg_,depth,display);
     if(copyPixmapDataWithKey(buf)==MSFalse) 
       create(pServer_,MSPixmap::SolidBackgroundPixmap,fg_,bg_);
   }
}

void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_,
		      int w_,int h_,unsigned long fg_,unsigned long bg_)
{
  int dep=DefaultDepthOfScreen(pServer_->screen());
  Pixmap p=XCreatePixmap(pServer_->display(),pServer_->root(),w_,h_,dep);
  create(pServer_,pName_,p,w_,h_,dep,fg_,bg_);
}
Esempio n. 17
0
IdType MetadataStream::add( std::shared_ptr< MetadataInternal >& spMetadataInternal)
{
    if( !this->getSchema(spMetadataInternal->getDesc()->getSchemaName()) )
	VMF_EXCEPTION(vmf::NotFoundException, "Metadata schema is not in the stream");

    IdType id = spMetadataInternal->getId();
    if(id != INVALID_ID)
    {
        if(this->getById(id) == nullptr)
        {
            if(nextId < id)
                nextId = id + 1;
        }
        else
            VMF_EXCEPTION(IncorrectParamException, "Metadata with such id is already in the stream");
    }
    else
    {
        id = nextId++;
        spMetadataInternal->setId(id);
    }
    internalAdd(spMetadataInternal);
    addedIds.push_back(id);

    if(!spMetadataInternal->vRefs.empty())
    {
        auto spItem = getById(id);
        for(auto ref = spMetadataInternal->vRefs.begin(); ref != spMetadataInternal->vRefs.end(); ref++)
        {
            auto referencedItem = getById(ref->first);
            if(referencedItem != nullptr)
                spItem->addReference(referencedItem, ref->second);
            else
                m_pendingReferences[ref->first].push_back(std::make_pair(id, ref->second));
        }
    }
    auto pendingReferences = m_pendingReferences[id];
    if(!pendingReferences.empty())
    {
        for(auto pendingId = pendingReferences.begin(); pendingId != pendingReferences.end(); pendingId++)
            getById(pendingId->first)->addReference(spMetadataInternal, pendingId->second);
        m_pendingReferences[id].clear();
        m_pendingReferences.erase(id);
    }

    return id;
}
Esempio n. 18
0
void MSPixmap::create(MSDisplayServer *pServer_,const char *pName_)
{
  char buf[255];
  char *bitmap;
  if ((unsigned long)(bitmap=(char *)_pPixmapHashTable->lookup(pName_))==_pPixmapHashTable->notFound())
   {
     MSMessageLog::criticalMessage("MSPixmap error: Unable to create prdefined Pixmap `%s' - unknown name\n",pName_);
     applicationExit();
   }
  else
   {
     int w=PredefinedPixmapWidth;
     int h=PredefinedPixmapHeight; 
     sprintf(buf,"Predefined_%s_%d_%d",pName_,1,pServer_->display());
     Pixmap p=XCreateBitmapFromData(pServer_->display(),pServer_->root(),(char *)bitmap,w,h);
     _pData=new MSPixmapData(pServer_,buf,p,p,w,h,1,0,0);
     addToHashTable(buf,(void *)_pData);
     addReference();
   }
}
Esempio n. 19
0
bool ListShapeSetter::parseShape(const hkpShape* s)
{
	auto shape = dynamic_cast<const hkpListShape*>(s);
	if(!shape) return false;
	
	ui->listWidget->clear();
	for(int i=0; i<children.getSize(); ++i)
		children[i]->removeReference();
	children.clear();
	
	hkpShapeBuffer buffer;
	for(hkpShapeKey key = shape->getFirstKey(); key!=HK_INVALID_SHAPE_KEY; key = shape->getNextKey(key))
	{
		auto child = shape->getChildShape(key, buffer);
		child->addReference();
		auto shapeClass = getHavokClass(child);
		ui->listWidget->addItem(new QListWidgetItem(shapeClass->getName()));
		children.pushBack(child);
	}
	return true;
}
Esempio n. 20
0
void BaseTagHDF5::references(const std::vector<DataArray> &refs_new) {

    // extract vectors of names from vectors of new & old references
    std::vector<std::string> names_new(refs_new.size());
    transform(refs_new.begin(), refs_new.end(), names_new.begin(), util::toName<DataArray>);
	//FIXME: issue 473
    std::vector<DataArray> refs_old(static_cast<size_t>(referenceCount()));
    for (size_t i = 0; i < refs_old.size(); i++) refs_old[i] = getReference(i);
    std::vector<std::string> names_old(refs_old.size());
    transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);

    // sort them
    std::sort(names_new.begin(), names_new.end());
    std::sort(names_new.begin(), names_new.end());

    // get names only in names_new (add), names only in names_old (remove) & ignore rest
    std::vector<std::string> names_add;
    std::vector<std::string> names_rem;
    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),
            std::inserter(names_add, names_add.begin()));
    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),
            std::inserter(names_rem, names_rem.begin()));

    // check if all new references exist & add sources
    auto blck = dynamic_pointer_cast<BlockHDF5>(block());
    for (auto name : names_add) {
        if (!blck->hasDataArray(name))
            throw std::runtime_error("One or more data arrays do not exist in this block!");
        addReference(blck->getDataArray(name)->id());
    }
    // remove references
    for (auto name : names_rem) {
        if (!blck->hasDataArray(name))
            removeReference(blck->getDataArray(name)->id());
    }
}
Esempio n. 21
0
  std::error_code perform(SimpleFile &mergedFile) override {
    // Skip this pass if output format uses text relocations instead of stubs.
    if (!this->noTextRelocs())
      return std::error_code();

    // Scan all references in all atoms.
    for (const DefinedAtom *atom : mergedFile.defined()) {
      for (const Reference *ref : *atom) {
        // Look at call-sites.
        if (!this->isCallSite(*ref))
          continue;
        const Atom *target = ref->target();
        assert(target != nullptr);
        if (isa<SharedLibraryAtom>(target)) {
          // Calls to shared libraries go through stubs.
          _targetToUses[target].push_back(ref);
          continue;
        }
        const DefinedAtom *defTarget = dyn_cast<DefinedAtom>(target);
        if (defTarget && defTarget->interposable() != DefinedAtom::interposeNo){
          // Calls to interposable functions in same linkage unit must also go
          // through a stub.
          assert(defTarget->scope() != DefinedAtom::scopeTranslationUnit);
          _targetToUses[target].push_back(ref);
        }
      }
    }

    // Exit early if no stubs needed.
    if (_targetToUses.empty())
      return std::error_code();

    // First add help-common and GOT slots used by lazy binding.
    SimpleDefinedAtom *helperCommonAtom =
        new (_file.allocator()) StubHelperCommonAtom(_file, _stubInfo);
    SimpleDefinedAtom *helperCacheNLPAtom =
        new (_file.allocator()) NonLazyPointerAtom(_file, _ctx.is64Bit());
    SimpleDefinedAtom *helperBinderNLPAtom =
        new (_file.allocator()) NonLazyPointerAtom(_file, _ctx.is64Bit());
    addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
                 helperCacheNLPAtom);
    addOptReference(
        helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
        _stubInfo.optStubHelperCommonReferenceToCache, helperCacheNLPAtom);
    addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
                 helperBinderNLPAtom);
    addOptReference(
        helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
        _stubInfo.optStubHelperCommonReferenceToBinder, helperBinderNLPAtom);
    mergedFile.addAtom(*helperCommonAtom);
    mergedFile.addAtom(*helperBinderNLPAtom);
    mergedFile.addAtom(*helperCacheNLPAtom);

    // Add reference to dyld_stub_binder in libSystem.dylib
    auto I = std::find_if(
        mergedFile.sharedLibrary().begin(), mergedFile.sharedLibrary().end(),
        [&](const SharedLibraryAtom *atom) {
          return atom->name().equals(_stubInfo.binderSymbolName);
        });
    assert(I != mergedFile.sharedLibrary().end() &&
           "dyld_stub_binder not found");
    addReference(helperBinderNLPAtom, _stubInfo.nonLazyPointerReferenceToBinder, *I);

    // Sort targets by name, so stubs and lazy pointers are consistent
    std::vector<const Atom *> targetsNeedingStubs;
    for (auto it : _targetToUses)
      targetsNeedingStubs.push_back(it.first);
    std::sort(targetsNeedingStubs.begin(), targetsNeedingStubs.end(),
              [](const Atom * left, const Atom * right) {
      return (left->name().compare(right->name()) < 0);
    });

    // Make and append stubs, lazy pointers, and helpers in alphabetical order.
    unsigned lazyOffset = 0;
    for (const Atom *target : targetsNeedingStubs) {
      auto *stub = new (_file.allocator()) StubAtom(_file, _stubInfo);
      auto *lp =
          new (_file.allocator()) LazyPointerAtom(_file, _ctx.is64Bit());
      auto *helper = new (_file.allocator()) StubHelperAtom(_file, _stubInfo);

      addReference(stub, _stubInfo.stubReferenceToLP, lp);
      addOptReference(stub, _stubInfo.stubReferenceToLP,
                      _stubInfo.optStubReferenceToLP, lp);
      addReference(lp, _stubInfo.lazyPointerReferenceToHelper, helper);
      addReference(lp, _stubInfo.lazyPointerReferenceToFinal, target);
      addReference(helper, _stubInfo.stubHelperReferenceToImm, helper);
      addReferenceAddend(helper, _stubInfo.stubHelperReferenceToImm, helper,
                         lazyOffset);
      addReference(helper, _stubInfo.stubHelperReferenceToHelperCommon,
                   helperCommonAtom);

      mergedFile.addAtom(*stub);
      mergedFile.addAtom(*lp);
      mergedFile.addAtom(*helper);

      // Update each reference to use stub.
      for (const Reference *ref : _targetToUses[target]) {
        assert(ref->target() == target);
        // Switch call site to reference stub atom instead.
        const_cast<Reference *>(ref)->setTarget(stub);
      }

      // Calculate new offset
      lazyOffset += target->name().size() + 12;
    }

    return std::error_code();
  }
Esempio n. 22
0
StimulusNodeGroup::StimulusNodeGroup(shared_ptr<StimulusGroup> group){
	for(int i = 0; i < group->getNElements(); i++){
		shared_ptr<StimulusNode> p(new StimulusNode(group->getElement(i)));
		addReference(p);
	} // TODO leaks
}
Esempio n. 23
0
    bool TextureReference::load(std::string aFilename, int aUnit, bool aUseUnit)
    {
        addReference();

        if(m_Texture != 0)
        {
            //Texture already here
            return false;
        }
        std::string textureName = aFilename;
        aFilename = FilePath::getInstance()->convertPathForTextures(aFilename);

		unsigned char * data;
        int width(0),height(0);
        data = SOIL_load_image(aFilename.c_str(),&width,&height,0,SOIL_LOAD_RGBA);
		//unsigned int error = lodepng_decode32_file(&data,&width,&height,aFilename.c_str());

        if(data == 0)
        {
            SOIL_free_image_data(data);
            removeReference();
            //failure to load texture remove reference
            return false;
        }
        unsigned int textureHandle = 0;

        glGenTextures(1, &textureHandle);
		if(aUseUnit == true)
		{
			glActiveTexture(GL_TEXTURE0 + aUnit);
		}
        glBindTexture(GL_TEXTURE_2D,textureHandle);
        glTexImage2D(GL_TEXTURE_2D,
                    0,
                    GL_RGBA,
                    width,
                    height,
                    0,
                    GL_RGBA,
                    GL_UNSIGNED_BYTE,
                    data);
        SOIL_free_image_data(data);
        
        //GL_CLAMP - Does not repeat, just stretches lines
        //GL_REPEAT - repeats.. checker board pattern
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //GL_CLAMP / GL_CLAMP_TO_EDGE / GL_REPEAT / GL_MIRRORED_REPEAT
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //GL_CLAMP / GL_CLAMP_TO_EDGE GL_REPEAT / GL_MIRRORED_REPEAT
        //GL_LINEAR - Smooth
        //GL_NEAREST - 8 Bit graphics
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //GL_NEAREST / GL_LINEAR
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //GL_NEAREST / GL_LINEAR


		//the min filter is used whenever a surface is rendered with smaller dimensions that its corresponding texture
		//the mag filter is used whenever the surface is bigger than the texture being applied

        
        //Unbind
        glBindTexture(GL_TEXTURE_2D,0);

        m_Texture = new Texture();
        m_Texture->m_Filename = aFilename;
        m_Texture->m_TextureName = textureName;
        m_Texture->m_ID = textureHandle;
        m_Texture->m_FileWidth = width;
        m_Texture->m_FileHeight = height;

        m_Texture->m_SourceX = 0;
        m_Texture->m_SourceY = 0;
        m_Texture->m_SourceWidth = m_Texture->m_FileWidth;
        m_Texture->m_SourceHeight = m_Texture->m_FileHeight;

        m_Texture->m_MinU = 0.0f;//m_Texture->m_SourceX / width;
        m_Texture->m_MaxU = 1.0f;//m_Texture->m_SourceY / width;
        m_Texture->m_MinV = 0.0f;//m_Texture->m_SourceWidth / height;
        m_Texture->m_MaxV = 1.0f;//m_Texture->m_SourceHeight / height;

        return true;
    }
OV_DLLFNCEXPORT UA_StatusCode propertyValueStatementOPCUAInterface_interface_ovExpressionSemanticNodeToOPCUA(
		void *handle, const UA_NodeId *nodeId, UA_Node** opcuaNode) {
	UA_Node 				*newNode = NULL;
	UA_StatusCode 			result = UA_STATUSCODE_GOOD;
	OV_PATH 				path;
	OV_INSTPTR_ov_object	pobj = NULL;
	OV_TICKET 				*pTicket = NULL;
	OV_VTBLPTR_ov_object	pVtblObj = NULL;
	OV_ACCESS				access;
	UA_NodeClass 			nodeClass;
	OV_ELEMENT				element;

	ov_memstack_lock();
	result = opcua_nodeStoreFunctions_resolveNodeIdToPath(*nodeId, &path);
	if(result != UA_STATUSCODE_GOOD){
		ov_memstack_unlock();
		return result;
	}
	element = path.elements[path.size-1];
	ov_memstack_unlock();
	result = opcua_nodeStoreFunctions_getVtblPointerAndCheckAccess(&(element), pTicket, &pobj, &pVtblObj, &access);
	if(result != UA_STATUSCODE_GOOD){
		return result;
	}

	nodeClass = UA_NODECLASS_VARIABLE;
	newNode = (UA_Node*)UA_calloc(1, sizeof(UA_VariableNode));


	// Basic Attribute
	// BrowseName
	UA_QualifiedName qName;
	qName.name = UA_String_fromChars(pobj->v_identifier);
	qName.namespaceIndex = nodeId->namespaceIndex;
	newNode->browseName = qName;

	// Description
	// Description
	OV_STRING tempString = pVtblObj->m_getcomment(pobj, &element);
	UA_LocalizedText lText;
	UA_LocalizedText_init(&lText);
	lText.locale = UA_String_fromChars("en");
	if(tempString){
		lText.text = UA_String_fromChars(tempString);
	} else {
		lText.text = UA_String_fromChars("");
	}
	UA_LocalizedText_copy(&lText,&newNode->description);
	UA_LocalizedText_deleteMembers(&lText);

	// DisplayName
	UA_LocalizedText displayName;
	UA_LocalizedText_init(&displayName);
	displayName.locale = UA_String_fromChars("en");
	displayName.text = UA_String_fromChars(pobj->v_identifier);
	UA_LocalizedText_copy(&displayName, &newNode->displayName);
	UA_LocalizedText_deleteMembers(&displayName);

	// NodeId
	UA_NodeId_copy(nodeId, &newNode->nodeId);

	// NodeClass
	newNode->nodeClass 	= nodeClass;

	// WriteMask
	UA_UInt32 writeMask = 0;
	if(element.elemtype != OV_ET_VARIABLE){
		if(access & OV_AC_WRITE){
			writeMask |= (1<<2);	//	BrowseName
			writeMask |= (1<<6);	//	DisplayName
		}
		if(access & OV_AC_RENAMEABLE){
			writeMask |= (1<<14);	//	NodeId
		}
	}
	newNode->writeMask 	= writeMask;

	// Variable specific attributes
	// arrayDemensions
	((UA_VariableNode*)newNode)->arrayDimensionsSize = 0;
	((UA_VariableNode*)newNode)->arrayDimensions = NULL; // UA_Array_new(((UA_VariableNode*)newNode)->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]);	/*	scalar or one dimension	*/

	// valuerank
	((UA_VariableNode*)newNode)->valueRank = 1;	/*	one dimension	*/


	// value
	OV_ELEMENT tmpPart;
	tmpPart.elemtype = OV_ET_NONE;
	OV_ELEMENT tmpParrent;
	tmpParrent.pobj = pobj;
	tmpParrent.elemtype = OV_ET_OBJECT;
	UA_ExpressionSemanticEnum tmpExpressionSemantic = 0;
	do {
		ov_element_getnextpart(&tmpParrent, &tmpPart, OV_ET_VARIABLE);
		if (tmpPart.elemtype == OV_ET_NONE)
			break;
		if (ov_string_compare(tmpPart.elemunion.pvar->v_identifier, "ExpressionSemanticEnum") == OV_STRCMP_EQUAL){
			tmpExpressionSemantic = *(UA_UInt32*)tmpPart.pvalue;
			break;
		}
	} while(TRUE);


	((UA_Variant*)&((UA_VariableNode*)newNode)->value.data.value.value)->type = &UA_PROPERTYVALUESTATEMENT[UA_PROPERTYVALUESTATEMENT_EXPRESSIONSEMANTICENUM];
	((UA_Variant*)&((UA_VariableNode*)newNode)->value.data.value.value)->data = UA_ExpressionSemanticEnum_new();
	if (!((UA_Variant*)&((UA_VariableNode*)newNode)->value.data.value.value)->data){
		result = UA_STATUSCODE_BADOUTOFMEMORY;
		return result;
	}
	((UA_VariableNode*)newNode)->value.data.value.hasValue = TRUE;
	((UA_VariableNode*)newNode)->valueSource = UA_VALUESOURCE_DATA;
	UA_ExpressionSemanticEnum_copy(&tmpExpressionSemantic, ((UA_Variant*)&((UA_VariableNode*)newNode)->value.data.value.value)->data);
	UA_ExpressionSemanticEnum_deleteMembers(&tmpExpressionSemantic);


	// accessLevel
	UA_Byte accessLevel = 0;
	if(access & OV_AC_READ){
		accessLevel |= (1<<0);
	}
	if(access & OV_AC_WRITE){
		accessLevel |= (1<<1);
	}
	((UA_VariableNode*)newNode)->accessLevel = accessLevel;
	// minimumSamplingInterval
	((UA_VariableNode*)newNode)->minimumSamplingInterval = -1;
	// historizing
	((UA_VariableNode*)newNode)->historizing = UA_FALSE;
	// dataType
	((UA_VariableNode*)newNode)->dataType = UA_NODEID_NUMERIC(pinterface->v_modelnamespace.index, UA_NSPROPERTYVALUESTATEMENTID_EXPRESSIONSEMANTICENUM);


	// References
	addReference(newNode);
	OV_UINT len = 0;
	OV_STRING *plist = NULL;
	OV_STRING tmpString = NULL;
	copyOPCUAStringToOV(nodeId->identifier.string, &tmpString);
	plist = ov_string_split(tmpString, "/", &len);
	ov_string_setvalue(&tmpString, plist[0]);
	for (OV_UINT i = 1; i < len-1; i++){
		ov_string_append(&tmpString, "/");
		ov_string_append(&tmpString, plist[i]);
	}
	ov_string_freelist(plist);
	UA_NodeId tmpNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASTYPEDEFINITION);
	for (size_t i = 0; i < newNode->referencesSize; i++){
		if (UA_NodeId_equal(&newNode->references[i].referenceTypeId, &tmpNodeId)){
			newNode->references[i].targetId = UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_PROPERTYTYPE);
			continue;
		}
		OV_STRING tmpString2 = NULL;
		copyOPCUAStringToOV(newNode->references[i].targetId.nodeId.identifier.string, &tmpString2);
		if (ov_string_compare(tmpString, tmpString2) == OV_STRCMP_EQUAL &&
			newNode->references[i].isInverse == UA_TRUE){
			newNode->references[i].referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
		}
		ov_string_setvalue(&tmpString2, NULL);
	}
	ov_string_setvalue(&tmpString, NULL);
	UA_NodeId_deleteMembers(&tmpNodeId);

	*opcuaNode = newNode;
	return UA_STATUSCODE_GOOD;
}
void AudioPlainTextBuilder::addAudioTag(const QString& source)
{
  int ref = addReference( source );

  appendRawText( QString( "[%1]" ).arg( ref ) );
}