Ejemplo n.º 1
0
	/*
	 * Adds node to routing table
	 */
	bool KBucket::insert(const Node::Ptr& node)
	{
		if(node->isInList)
			return true;	// node is already in the table

		string ip = node->getIdentity().getIp();
		string port = node->getIdentity().getUdpPort();

		// allow only one same IP:port
		bool isAcceptable = (ipMap.find(ip + ":" + port) == ipMap.end());

		if((nodes.size() < (K * ID_BITS)) && isAcceptable)
		{
			nodes.push_back(node);
			node->isInList = true;
			ipMap.insert(ip + ":" + port);

			if(DHT::getInstance())
				DHT::getInstance()->setDirty();

			return true;
		}

		return isAcceptable;
	}
Ejemplo n.º 2
0
void XercesUpdateFactory::addToPutSet(const Node::Ptr &node, const LocationInfo *location, DynamicContext *context)
{
  Node::Ptr root = node->root(context);

  Sequence docURISeq = root->dmDocumentURI(context);
  const XMLCh *docuri = 0;
  if(!docURISeq.isEmpty()) {
    docuri = docURISeq.first()->asString(context);
  }

  PutItem item(docuri, root, location, context);

  std::pair<PutSet::iterator, bool> res = putSet_.insert(item);
  if(!res.second && !res.first->node->equals(item.node)) {
    if(context->getMessageListener() != 0) {
      context->getMessageListener()->warning(X("In the context of this expression"), res.first->location);
    }

    XMLBuffer buf;
    buf.append(X("Document writing conflict for URI \""));
    buf.append(item.uri);
    buf.append(X("\""));

    XQThrow3(ASTException, X("XercesUpdateFactory::addToPutSet"), buf.getRawBuffer(), location);
  }
}
	/*
	 * Sends request to create connection with me
	 */
	void ConnectionManager::revConnectToMe(const Node::Ptr& node, const AdcCommand& cmd)
	{
		// don't allow connection if we didn't proceed a handshake
		//if(!node->isOnline())
		//	return;

		// this is valid for active-passive connections only
		if(!ClientManager::getInstance()->isActive())
			return;
			
		const string& protocol = cmd.getParam(1);
		const string& token = cmd.getParam(2);

		bool secure;
		if(protocol == CLIENT_PROTOCOL)
		{
			secure = false;
		}
		else if(protocol == SECURE_CLIENT_PROTOCOL_TEST && CryptoManager::getInstance()->TLSOk())
		{
			secure = true;
		}
		else
		{
			AdcCommand sta(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_UNSUPPORTED, "Protocol unknown", AdcCommand::TYPE_UDP);
			sta.addParam("PR", protocol);
			sta.addParam("TO", token);

			DHT::getInstance()->send(sta, node->getIdentity().getIp(), static_cast<uint16_t>(Util::toInt(node->getIdentity().getUdpPort())), 
				node->getUser()->getCID(), node->getUdpKey());
			return;
		}
		
		connect(node, token, secure);
	}
Ejemplo n.º 4
0
Sequence FunctionLocalname::createSequence(DynamicContext* context, int flags) const
{
  XPath2MemoryManager* memMgr = context->getMemoryManager();

  Node::Ptr ctxNode;
  if(getNumArgs() == 1) {
    Sequence arg=getParamNumber(1,context)->toSequence(context);
    if(arg.isEmpty())
      return Sequence(context->getItemFactory()->createString(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgZeroLenString, context), memMgr);
    ctxNode=arg.first();
  }
  else {
    const Item::Ptr item = context->getContextItem();
    if(item==NULLRCP)
      XQThrow(FunctionException, X("FunctionLocalName::createSequence"),X("Undefined context item in fn:local-name [err:XPDY0002]"));
    if(!item->isNode())
      XQThrow(FunctionException, X("FunctionLocalName::createSequence"),X("The context item is not a node [err:XPTY0004]"));
    ctxNode=item;
	}

  ATQNameOrDerived::Ptr name = ctxNode->dmNodeName(context);
  if(name.notNull())
    return Sequence(context->getItemFactory()->createString(((const ATQNameOrDerived*)name.get())->getName(), context), memMgr);

  return Sequence(context->getItemFactory()->createString(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgZeroLenString, context), memMgr);
}
Ejemplo n.º 5
0
Item::Ptr UTransform::TransformResult::next(DynamicContext *context)
{
    context->testInterrupt();

    AutoVariableStoreReset reset(context, &scope_);

    if(toDo_) {
        toDo_ = false;

        NodeSet copiedNodes = NodeSet(nodecompare(context));

        VectorOfCopyBinding::const_iterator end = transform_->getBindings()->end();
        for(VectorOfCopyBinding::const_iterator it = transform_->getBindings()->begin();
                it != end; ++it) {
            if((*it)->qname_ == 0) continue;

            Sequence values = (*it)->expr_->createResult(context)->toSequence(context);

            // Keep a record of the nodes that have been copied
            Result valIt = values;
            Item::Ptr val;
            while((val = valIt->next(context)).notNull()) {
                copiedNodes.insert((Node*)val.get());
            }

            scope_.setVar((*it)->uri_, (*it)->name_, values);
        }

        // Get the pending update list
        PendingUpdateList pul = transform_->getModifyExpr()->createUpdateList(context);

        // Check that the targets of the pending updates are copied nodes
        for(PendingUpdateList::const_iterator i = pul.begin(); i != pul.end(); ++i) {
            Node::Ptr target = i->getTarget();
            while(copiedNodes.find(target) == copiedNodes.end()) {
                target = target->dmParent(context);
                if(target.isNull()) {
                    XQThrow3(StaticErrorException,X("UTransform::staticTyping"),
                             X("The target node of an update expression in the transform expression is not a node from the copy clauses [err:XUDY0014]"), &(*i));
                }
            }
        }

        // Apply the updates
        AutoDelete<UpdateFactory> ufactory(context->createUpdateFactory());
        ufactory->applyUpdates(pul, context, transform_->getRevalidationMode());

        // Execute the return expression
        result_ = transform_->getReturnExpr()->createResult(context);
    }

    Item::Ptr result = result_->next(context);

    if(result.isNull()) {
        result_ = 0;
        return 0;
    }

    return result;
}
Ejemplo n.º 6
0
PendingUpdateList UInsertAsLast::createUpdateList(DynamicContext *context) const
{
  Node::Ptr node = (Node*)target_->createResult(context)->next(context).get();

  if(node->dmNodeKind() != Node::element_string &&
     node->dmNodeKind() != Node::document_string)
    XQThrow(XPath2TypeMatchException,X("UInsertAsLast::createUpdateList"),
            X("It is a type error for the target expression of an insert as last expression not to be a single element "
              "or document [err:XUTY0005]"));

  Sequence alist(context->getMemoryManager());
  Sequence clist(context->getMemoryManager());

  Result value = source_->createResult(context);
  Item::Ptr item;
  while((item = value->next(context)).notNull()) {
    if(((Node*)item.get())->dmNodeKind() == Node::attribute_string) {
      if(!clist.isEmpty())
        XQThrow(ASTException,X("UInsertAsLast::createUpdateList"),
                X("Attribute nodes must occur before other nodes in the source expression for an insert as last expression [err:XUTY0004]"));

      //    b. No attribute node in $alist may have a QName whose implied namespace binding conflicts with a namespace
      //       binding in the "namespaces" property of $target [err:XUDY0023].  
      ATQNameOrDerived::Ptr qname = ((Node*)item.get())->dmNodeName(context);
      if(qname->getURI() != 0 && *(qname->getURI()) != 0) {
        ATAnyURIOrDerived::Ptr uri = FunctionNamespaceURIForPrefix::uriForPrefix(qname->getPrefix(), node, context, this);
        if(uri.notNull() && !XPath2Utils::equals(uri->asString(context), qname->getURI())) {
          XMLBuffer buf;
          buf.append(X("Implied namespace binding for the insert as last expression (\""));
          buf.append(qname->getPrefix());
          buf.append(X("\" -> \""));
          buf.append(qname->getURI());
          buf.append(X("\") conflicts with those already existing on the parent element of the target attribute [err:XUDY0023]"));
          XQThrow3(DynamicErrorException, X("UInsertInto::createUpdateList"), buf.getRawBuffer(), this);
        }
      }

      alist.addItem(item);
    }
    else
      clist.addItem(item);
  }

  PendingUpdateList result;

  if(!alist.isEmpty()) {
    // 3. If $alist is not empty and into is specified, the following checks are performed:
    //    a. $target must be an element node [err:XUTY0022].
    if(node->dmNodeKind() == Node::document_string)
      XQThrow(XPath2TypeMatchException,X("UInsertInto::createUpdateList"),
              X("It is a type error if an insert expression specifies the insertion of an attribute node into a document node [err:XUTY0022]"));
    result.addUpdate(PendingUpdate(PendingUpdate::INSERT_ATTRIBUTES, node, alist, this));
  }
  if(!clist.isEmpty()) {
    result.addUpdate(PendingUpdate(PendingUpdate::INSERT_INTO_AS_LAST, node, clist, this));
  }

  return result;
}
Ejemplo n.º 7
0
PendingUpdateList UReplaceValueOf::createUpdateList(DynamicContext *context) const
{
  Node::Ptr node = (Node*)target_->createResult(context)->next(context).get();

  if(node->dmNodeKind() == Node::document_string)
    XQThrow(XPath2TypeMatchException,X("UReplaceValueOf::createUpdateList"),
            X("The target expression of a replace expression does not return a single "
              "node that is not a document node [err:XUTY0008]"));
    
  XMLBuffer buf;
  XQDOMConstructor::getStringValue(expr_, buf, context);

  // If $target is a comment node, and $string contains two adjacent hyphens or ends with a hyphen, a dynamic error is raised [err:XQDY0072].
  if(node->dmNodeKind() == Node::comment_string) {
    bool foundOne = false;
    for(const XMLCh *str = buf.getRawBuffer(); *str; ++str) {
      if(*str == '-') {
        if(foundOne) {
          XQThrow(DynamicErrorException,X("UReplaceValueOf::createUpdateList"),
                  X("The replace value of expression would result in a comment node whose content contains two adjacent hyphens [err:XQDY0072]"));
        }
        else foundOne = true;
      }
      else {
        foundOne = false;
      }
    }

    if(foundOne) {
      XQThrow(DynamicErrorException,X("UReplaceValueOf::createUpdateList"),
              X("The replace value of expression would result in a comment node whose content ends with a hyphen [err:XQDY0072]"));
    }
  }
  // If $target is a processing instruction node, and $string contains the substring "?>", a dynamic error is raised [err:XQDY0026].
  else if(node->dmNodeKind() == Node::processing_instruction_string) {
    bool foundQuestion = false;
    for(const XMLCh *str = buf.getRawBuffer(); *str; ++str) {
      if(*str == '?') {
        foundQuestion = true;
      }
      else {
        if(foundQuestion && *str == '>') {
          XQThrow(DynamicErrorException,X("UReplaceValueOf::createUpdateList"),
                  X("The replace value of expression would result in a processing instruction node whose content includes the string \"?>\" [err:XQDY0026]"));
        }
        foundQuestion = false;
      }
    }
  }

  Item::Ptr value = context->getItemFactory()->createString(buf.getRawBuffer(), context);

  if(node->dmNodeKind() == Node::element_string) {
    return PendingUpdate(PendingUpdate::REPLACE_ELEMENT_CONTENT, node, value, this);
  }
  else {
    return PendingUpdate(PendingUpdate::REPLACE_VALUE, node, value, this);
  }
}
Ejemplo n.º 8
0
	bool operator()(const Node::Ptr& lhs, const Node::Ptr& rhs)
	{
		auto costFgv1 = lhs->costFgv();
		auto costFgv2 = rhs->costFgv();

		if (costFgv1 == costFgv2) {
			return lhs->time < rhs->time;
		}
		return costFgv1 > costFgv2;
	}
Ejemplo n.º 9
0
    void ConnectionManager::connect(const Node::Ptr& node, const string& token, bool secure)
    {
        // don't allow connection if we didn't proceed a handshake
        if(!node->isOnline())
        {
            // do handshake at first
            DHT::getInstance()->info(node->getIdentity().getIp(), node->getIdentity().getUdpPort(),
                DHT::PING | DHT::MAKE_ONLINE, node->getUser()->getCID(), node->getUdpKey());
            return;
        }

        bool active = ClientManager::getInstance()->isActive();

        // if I am not active, send reverse connect to me request
        AdcCommand cmd(active ? AdcCommand::CMD_CTM : AdcCommand::CMD_RCM, AdcCommand::TYPE_UDP);
        cmd.addParam(secure ? SECURE_CLIENT_PROTOCOL_TEST : CLIENT_PROTOCOL);

        if(active)
        {
            string port = secure ? dcpp::ConnectionManager::getInstance()->getSecurePort() : dcpp::ConnectionManager::getInstance()->getPort();
            cmd.addParam(port);
        }

        cmd.addParam(token);

        DHT::getInstance()->send(cmd, node->getIdentity().getIp(), node->getIdentity().getUdpPort(),
            node->getUser()->getCID(), node->getUdpKey());
    }
Ejemplo n.º 10
0
bool SequenceType::ItemType::matchesSchemaElement(const Node::Ptr &toBeTested, const DynamicContext* context) const
{
  // retrieve the type of the element name
  assert(m_pName!=NULL);
  const XMLCh* elementNS=m_NameURI;
  const XMLCh* elementName=m_pName->getName();
  SchemaElementDecl *elemDecl=context->getDocumentCache()->getElementDecl(elementNS, elementName);
  assert(elemDecl != NULL);

  // 1. The name of the candidate node matches the specified ElementName or matches the name of an element in a 
  //    substitution group headed by an element named ElementName.
  ATQNameOrDerived::Ptr name = toBeTested->dmNodeName(context);
  if(name.isNull()) return false;
  const XMLCh *node_uri = ((const ATQNameOrDerived*)name.get())->getURI();
  const XMLCh *node_name = ((const ATQNameOrDerived*)name.get())->getName();

  if(!(XPath2Utils::equals(elementName, node_name)) ||
     !(XPath2Utils::equals(elementNS, node_uri)))
  {
    // the node doesn't match the ElementName; check if it is in its substitution group
    SchemaElementDecl* thisElemDecl=context->getDocumentCache()->getElementDecl(node_uri, node_name);
    if(thisElemDecl==NULL) // the node to be tested has no type info
      return false;

    SchemaElementDecl* rootElemDecl=thisElemDecl->getSubstitutionGroupElem();
    bool foundIt=false;
    while (rootElemDecl)
    {
      if (XPath2Utils::equals(rootElemDecl->getBaseName(), elementName) &&
          XPath2Utils::equals(context->getDocumentCache()->getSchemaUri(rootElemDecl->getURI()), elementNS))
      {
        foundIt = true;
        break;
      }

      rootElemDecl = rootElemDecl->getSubstitutionGroupElem();
    }
    if(!foundIt)
      return false;
  }

  // 2. derives-from(AT, ET) is true, where AT is the type of the candidate node and ET is the type declared for 
  //    element ElementName in the in-scope element declarations.
  ComplexTypeInfo* pTypeInfo=elemDecl->getComplexTypeInfo();
  if(pTypeInfo && !toBeTested->hasInstanceOfType(pTypeInfo->getTypeUri(), pTypeInfo->getTypeLocalName(), context))
    return false;

  // 3. Either the nilled property of the candidate node is false, or the element declaration for ElementName in 
  //    the in-scope element declarations is nillable.
  if(toBeTested->dmNilled(context).get()->isTrue() &&
     !(elemDecl->getMiscFlags() & SchemaSymbols::XSD_NILLABLE))
    return false;
      
  return true;
}
Ejemplo n.º 11
0
bool BoundFactsCalculator::HasIncomingEdgesFromLowerLevel(int curOrder, vector<Node::Ptr>& curNodes) {
    for (auto nit = curNodes.begin(); nit != curNodes.end(); ++nit) {
        Node::Ptr cur = *nit;
	NodeIterator nbegin, nend;
	cur->ins(nbegin, nend);
	for (; nbegin != nend; ++nbegin)
	    if (analysisOrder[*nbegin] < curOrder) return true;
    }
    return false;

}
Ejemplo n.º 12
0
bool XercesURIResolver::resolveDocument(Sequence &result, const XMLCh* uri, DynamicContext* context, const QueryPathNode *projection)
{
  Node::Ptr doc;

  // Resolve the uri against the base uri
  const XMLCh *systemId = uri;
  XMLURL urlTmp(context->getMemoryManager());
  if(urlTmp.setURL(context->getBaseURI(), uri, urlTmp)) {
    systemId = context->getMemoryManager()->getPooledString(urlTmp.getURLText());
  } else {
	systemId = context->getMemoryManager()->getPooledString(uri);
  }

  // Check in the cache
  DOMDocument *found = _documentMap.get((void*)systemId);

  // Check to see if we can locate and parse the document
  if(found == 0) {
    try {
      doc = const_cast<DocumentCache*>(context->getDocumentCache())->loadDocument(uri, context, projection);

      found = (DOMDocument*)((DOMNode*)doc->getInterface(XercesConfiguration::gXerces));

      _documentMap.put((void*)systemId, found);
      _uriMap.put((void*)found, const_cast<XMLCh*>(systemId));
    }
    catch(const XMLParseException& e) {
      XMLBuffer errMsg;
      errMsg.set(X("Error parsing resource: "));
      errMsg.append(uri);
      errMsg.append(X(". Error message: "));
      errMsg.append(e.getError());
      errMsg.append(X(" [err:FODC0002]"));
      XQThrow2(XMLParseException,X("XercesContextImpl::resolveDocument"), errMsg.getRawBuffer());
    }
  }
  else {
    doc = new XercesNodeImpl(found, (XercesURIResolver*)context->getDefaultURIResolver());
  }

  if(doc.notNull()) {
    result.addItem(doc);
    return true;
  }

  XMLBuffer errMsg;
  errMsg.set(X("Error retrieving resource: "));
  errMsg.append(uri);
  errMsg.append(X(" [err:FODC0002]"));
  XQThrow2(XMLParseException,X("XercesContextImpl::resolveDocument"), errMsg.getRawBuffer());

  return false;
}
Ejemplo n.º 13
0
void DbXmlUpdateFactory::applyInsertBefore(const PendingUpdate &update, DynamicContext *context)
{
	const DbXmlNodeImpl *next = (const DbXmlNodeImpl*)update.getTarget().get();
	if (!next->isUpdateAble())
		return;
	Node::Ptr parent = next->dmParent(context);
	NsDomNodeRef nextRef = next->getNsDomNode();
	applyInserts(update,
		     (const DbXmlNodeImpl *)parent->getInterface(DbXmlNodeImpl::gDbXml),
		     nextRef.get(),
		     context,
                     false);
}
Ejemplo n.º 14
0
static
std::string
getDotLabel(Node::Ptr node)
{
    if (node)
    {
        return node->name() == "unnamed" || node->name().find("AutoName$") != std::string::npos
            ? "\"\""
            : "\"" + node->name() + "\"";
    }
    else
        return "\"\"";
}
Ejemplo n.º 15
0
void DbXmlUpdateFactory::applyReplaceNode(const PendingUpdate &update, DynamicContext *context)
{
	const DbXmlNodeImpl *target = (const DbXmlNodeImpl*)update.getTarget().get();
	if (!target->isUpdateAble())
		return;
	Node::Ptr parent = target->dmParent(context);
	// insert all new nodes *before* the target, then
	// mark target for deletion
	NsDomNodeRef targetRef = target->getNsDomNode();
	applyInserts(update,
		     (const DbXmlNodeImpl *)parent->getInterface(DbXmlNodeImpl::gDbXml),
		     targetRef.get(),
		     context, false);
	forDeletion_.insert(target);
}
Ejemplo n.º 16
0
PendingUpdateList URename::createUpdateList(DynamicContext *context) const
{
  Node::Ptr node = (Node*)target_->createResult(context)->next(context).get();

  if(node->dmNodeKind() != Node::element_string &&
     node->dmNodeKind() != Node::attribute_string &&
     node->dmNodeKind() != Node::processing_instruction_string)
    XQThrow(XPath2TypeMatchException,X("URename::createUpdateList"),
            X("It is a type error for the target expression of a rename expression not to be a single element, "
              "attribute or processing instruction [err:XUTY0012]"));

  ATQNameOrDerived::Ptr qname = (ATQNameOrDerived*)name_->createResult(context)->next(context).get();

  // 3. The following checks are performed for error conditions:
  //    a. If $target is an element node, the "namespaces" property of $target must not include any namespace binding that conflicts
  //       with the implied namespace binding of $QName [err:XUDY0023].
  if(node->dmNodeKind() == Node::element_string) {
    ATAnyURIOrDerived::Ptr uri = FunctionNamespaceURIForPrefix::uriForPrefix(qname->getPrefix(), node, context, this);
    if(uri.notNull() && !XPath2Utils::equals(uri->asString(context), qname->getURI())) {
      XMLBuffer buf;
      buf.append(X("Implied namespace binding for the rename expression (\""));
      buf.append(qname->getPrefix());
      buf.append(X("\" -> \""));
      buf.append(qname->getURI());
      buf.append(X("\") conflicts with those already existing on the target element [err:XUDY0023]"));
      XQThrow3(DynamicErrorException, X("URename::createUpdateList"), buf.getRawBuffer(), this);
    }
  }
  //    b. If $target is an attribute node that has a parent, the "namespaces" property of parent($target) must not include any
  //       namespace binding that conflicts with the implied namespace binding of $QName [err:XUDY0023].
  else if(node->dmNodeKind() == Node::attribute_string) {
    Node::Ptr parentNode = node->dmParent(context);
    if(parentNode.notNull() && qname->getURI() != 0 && *(qname->getURI()) != 0) {
      ATAnyURIOrDerived::Ptr uri = FunctionNamespaceURIForPrefix::uriForPrefix(qname->getPrefix(), parentNode, context, this);
      if(uri.notNull() && !XPath2Utils::equals(uri->asString(context), qname->getURI())) {
        XMLBuffer buf;
        buf.append(X("Implied namespace binding for the rename expression (\""));
        buf.append(qname->getPrefix());
        buf.append(X("\" -> \""));
        buf.append(qname->getURI());
        buf.append(X("\") conflicts with those already existing on the parent element of the target attribute [err:XUDY0023]"));
        XQThrow3(DynamicErrorException, X("URename::createUpdateList"), buf.getRawBuffer(), this);
      }
    }
  }
  //    c. If $target is processing instruction node, $QName must not include a non-empty namespace prefix. [err:XUDY0025].
  else if(node->dmNodeKind() == Node::processing_instruction_string && !XPath2Utils::equals(qname->getPrefix(), XMLUni::fgZeroLenString))
    XQThrow(XPath2TypeMatchException,X("URename::createUpdateList"),
            X("The target of a rename expression is a processing instruction node, and the new name "
              "expression returned a QName with a non-empty namespace prefix [err:XUDY0025]"));

  return PendingUpdate(PendingUpdate::RENAME, node, qname, this);
}
Ejemplo n.º 17
0
void
addStar(Node::Ptr root, file::AssetLibrary::Ptr assets, std::vector<Star>& stars)
{
    const unsigned int MAX_NUM_STARS = 20;

    if (stars.size() == MAX_NUM_STARS)
    {
        std::cerr << "cannot add more stars." << std::endl;
        return;
    }

    unsigned int   numBranches = 4 + rand() % 4;
    float          outRadius = 0.9f + 0.2f * (rand() / float(RAND_MAX) - 0.5f);
    float          inRadius = outRadius * (0.5f + 0.1f * (rand() / float(RAND_MAX) - 0.5f));

    auto starNode = Node::create("star_" + std::to_string(stars.size()))
        ->addComponent(Surface::create(
            createStarLineGeometry(numBranches, inRadius, outRadius, assets->context()),
            material::Material::create("material")
                ->set("diffuseColor", Color::hslaToRgba(rand() / float(RAND_MAX), 0.75f, 0.6f, 1.0f))
                ->set("lineThickness", 1.0f + 3.0f * (rand() / float(RAND_MAX))),
            assets->effect("line")
        ))
        ->addComponent(Transform::create(Matrix4x4::create()->appendRotationZ(2.0f * float(M_PI) * rand() / (float) RAND_MAX)));

    stars.push_back(Star());

    stars.back().node = starNode;
    stars.back().angRate = 0.01f + 0.05f * (rand() / float(RAND_MAX));

    root->addChild(stars.back().node);
}
Ejemplo n.º 18
0
void
explodeModel(float        magnitude,
             float        previousMagnitude,
             Node::Ptr    node)
{
    assert(fabsf(magnitude) > 1e-6f);
    assert(fabsf(previousMagnitude) > 1e-6f);

    for (auto& child : node->children())
    {
        if (child->component<Transform>())
        {
            auto transform    = child->component<Transform>()->matrix();
            auto direction    = transform->translation();

            transform->appendTranslation(direction * (magnitude - previousMagnitude));

            explodeModel(magnitude * 0.8f, previousMagnitude * 0.8f, child);
        }
        else
        {
            explodeModel(magnitude, previousMagnitude, child);
        }
    }
}
boost::optional<EntityCollection<Cell>>
NodeConnectivity::getCellsAttachedToNode(Node::Ptr const & vertex) const {
    NodeCell_t::const_iterator it = node_cells_.find(vertex->id());
    if (it == node_cells_.end())
        return boost::optional<EntityCollection<Cell>>();

    return boost::optional<EntityCollection<Cell>>(it->second);
}
Ejemplo n.º 20
0
void XercesUpdateFactory::applyReplaceAttribute(const PendingUpdate &update, DynamicContext *context)
{
  const XercesNodeImpl *nodeImpl = (const XercesNodeImpl*)update.getTarget()->getInterface(Item::gXQilla);
  DOMAttr *domnode = (DOMAttr*)nodeImpl->getDOMNode();
  Node::Ptr parentNode = nodeImpl->dmParent(context);
  DOMElement *element = domnode->getOwnerElement();
  DOMDocument *doc = element->getOwnerDocument();

  bool untyped = parentNode->dmNodeKind() == Node::element_string &&
    XPath2Utils::equals(parentNode->getTypeName(), DocumentCache::g_szUntyped) &&
    XPath2Utils::equals(parentNode->getTypeURI(), SchemaSymbols::fgURI_SCHEMAFORSCHEMA);

  Result children = update.getValue();
  Item::Ptr item;
  while((item = children->next(context)).notNull()) {
    const XercesNodeImpl *childImpl = (const XercesNodeImpl*)item->getInterface(Item::gXQilla);
    DOMNode *newChild = importNodeFix(doc, const_cast<DOMNode*>(childImpl->getDOMNode()), /*deep*/true);

    // 1. Error checks:
    //    a. If the QNames of any two attribute nodes in $replacement have implied namespace bindings that conflict with
    //       each other, a dynamic error is raised [err:XUDY0024].
    //    b. If the QName of any attribute node in $replacement has an implied namespace binding that conflicts with a
    //       namespace binding in the "namespaces" property of parent($target), a dynamic error is raised [err:XUDY0024].
    // Checks performed by UpdateFactory

    // 2b. If the type-name property of parent($target) is xs:untyped, then upd:setToUntyped() is invoked
    //     on each element node in $replacement.
    if(!untyped) setTypes(newChild, childImpl->getDOMNode());

    // 2a. For each node in $replacement, the parent property is set to parent($target).
    // 4a. If $target is an attribute node, the attributes property of parent($target) is modified by removing $target
    //     and adding the nodes in $replacement (if any).
    // 4b. If $target is an attribute node, the namespaces property of parent($target) is modified to include namespace
    //     bindings for any attribute namespace prefixes in $replacement that did not already have bindings.
    element->setAttributeNode((DOMAttr*)newChild);
  }

  // 3a. $target is marked for deletion.
  forDeletion_.insert(domnode);

  // 4d. upd:removeType(parent($target)) is invoked.
  removeType(element);

  // Use parentNode, since the attr replace could have removed the original attr
  addToPutSet(parentNode, &update, context);
}
boost::optional<EntityCollection<Node>>
NodeConnectivity::getNodeNeighbors(Node::Ptr const & vertex) const {
    NodeNeighbor_t::const_iterator it = node_neighbors_.find(vertex->id());
    if (it == node_neighbors_.end())
        return boost::optional<EntityCollection<Node>>();

    return boost::optional<EntityCollection<Node>>(it->second);
}
Ejemplo n.º 22
0
void
bullet::PhysicsWorld::targetAddedHandler(AbstractComponent::Ptr controller,
                                         Node::Ptr                target)
{
    if (targets().size() > 1)
        throw std::logic_error("The same PhysicsWorld cannot be used twice.");

    setSceneManager(target->root()->component<SceneManager>());
}
Ejemplo n.º 23
0
void BoundFactsCalculator::ReverseDFS(Node::Ptr cur) {
    nodeColor[cur] = 1;
    analysisOrder[cur] = orderStamp;
    NodeIterator nbegin, nend;
    cur->ins(nbegin, nend);

    for (; nbegin != nend; ++nbegin)
        if (nodeColor.find(*nbegin) == nodeColor.end())
	    ReverseDFS(*nbegin);
}
Ejemplo n.º 24
0
void XercesUpdateFactory::applyInsertAfter(const PendingUpdate &update, DynamicContext *context)
{
  const XercesNodeImpl *nodeImpl = (const XercesNodeImpl*)update.getTarget()->getInterface(Item::gXQilla);
  DOMNode *domnode = const_cast<DOMNode*>(nodeImpl->getDOMNode());
  DOMNode *before = domnode->getNextSibling();
  Node::Ptr parentNode = nodeImpl->dmParent(context);
  DOMNode *parent = domnode->getParentNode();
  DOMDocument *doc = const_cast<DOMDocument*>(XPath2Utils::getOwnerDoc(domnode));

  bool untyped = parentNode->dmNodeKind() == Node::element_string &&
    XPath2Utils::equals(parentNode->getTypeName(), DocumentCache::g_szUntyped) &&
    XPath2Utils::equals(parentNode->getTypeURI(), SchemaSymbols::fgURI_SCHEMAFORSCHEMA);

  bool containsElementOrText = false;

  Result children = update.getValue();
  Item::Ptr item;
  while((item = children->next(context)).notNull()) {
    const XercesNodeImpl *childImpl = (const XercesNodeImpl*)item->getInterface(Item::gXQilla);
    DOMNode *newChild = importNodeFix(doc, const_cast<DOMNode*>(childImpl->getDOMNode()), /*deep*/true);

    if(childImpl->dmNodeKind() == Node::element_string ||
       childImpl->dmNodeKind() == Node::text_string) {
      containsElementOrText = true;
    }

    // If the type-name property of parent($target) is xs:untyped, then upd:setToUntyped() is invoked on each
    // element or attribute node in $content.
    if(!untyped) setTypes(newChild, childImpl->getDOMNode());

    // For each node in $content, the parent property is set to parent($target).
    // The children property of parent($target) is modified to add the nodes in $content just before $target,
    // preserving their order.
    parent->insertBefore(newChild, before);
  }

  // If at least one of the nodes in $content is an element or text node, upd:removeType(parent($target)) is invoked.
  if(containsElementOrText) {
    removeType(parent);
  }

  addToPutSet(update.getTarget(), &update, context);
}
Ejemplo n.º 25
0
    /*
     * Add new source to tth list
     */
    void IndexManager::addSource(const TTHValue& tth, const Node::Ptr& node, uint64_t size, bool partial)
    {
        Source source;
        source.setCID(node->getUser()->getCID());
        source.setIp(node->getIdentity().getIp());
        source.setUdpPort(node->getIdentity().getUdpPort());
        source.setSize(size);
        source.setExpires(GET_TICK() + (partial ? PFS_REPUBLISH_TIME : REPUBLISH_TIME));
        source.setPartial(partial);

        Lock l(cs);

        TTHMap::iterator i = tthList.find(tth);
        if(i != tthList.end())
        {
            // no user duplicites
            SourceList& sources = i->second;
            for(SourceList::iterator s = sources.begin(); s != sources.end(); ++s)
            {
                if(node->getUser()->getCID() == (*s).getCID())
                {
                    // delete old item
                    sources.erase(s);
                    break;
                }
            }

            // old items in front, new items in back
            sources.push_back(source);

            // if maximum sources reached, remove the oldest one
            if(sources.size() > MAX_SEARCH_RESULTS)
                sources.pop_front();
        }
        else
        {
            // new file
            tthList.insert(std::make_pair(tth, SourceList(1, source)));
        }

        DHT::getInstance()->setDirty();
    }
Ejemplo n.º 26
0
void
AbstractAnimation::targetAddedHandler(AbstractComponent::Ptr cmp, 
									  Node::Ptr node)
{
	_addedSlot = node->added()->connect(std::bind(
		&AbstractAnimation::addedHandler,
		shared_from_this(),
		std::placeholders::_1,
		std::placeholders::_2,
		std::placeholders::_3
	));

	_removedSlot = node->removed()->connect(std::bind(
		&AbstractAnimation::removedHandler,
		shared_from_this(),
		std::placeholders::_1,
		std::placeholders::_2,
		std::placeholders::_3
	));
}
Ejemplo n.º 27
0
void BoundFactsCalculator::NaturalDFS(Node::Ptr cur) {
    nodeColor[cur] = 1;
    NodeIterator nbegin, nend;
    cur->outs(nbegin, nend);

    for (; nbegin != nend; ++nbegin)
        if (nodeColor.find(*nbegin) == nodeColor.end())
	    NaturalDFS(*nbegin);

    reverseOrder.push_back(cur);

}
Ejemplo n.º 28
0
void DbXmlUpdateFactory::applyInsertAfter(const PendingUpdate &update, DynamicContext *context)
{
	const DbXmlNodeImpl *prev = (const DbXmlNodeImpl*)update.getTarget().get();
	if (!prev->isUpdateAble())
		return;
	Node::Ptr parent = prev->dmParent(context);
	// in order to preserve order for multiple inserts, insertAfter must turn
	// into insertBefore
	NsDomNodeRef prevRef = prev->getNsDomNode();
       NsDomNodeRef nextRef = prevRef->getNsNextSibling();
       if (!nextRef.get()) {
              DbXmlConfiguration *conf = GET_CONFIGURATION(context);
              prevRef->refreshNode(conf->getOperationContext(), true);
              nextRef = prevRef->getNsNextSibling();
       }
	applyInserts(update,
		     (const DbXmlNodeImpl *)parent->getInterface(DbXmlNodeImpl::gDbXml),
		     nextRef.get(),
		     context,
                     true);
}
Ejemplo n.º 29
0
    /*
     * Processes incoming request to publish file
     */
    void IndexManager::processPublishSourceRequest(const Node::Ptr& node, const AdcCommand& cmd)
    {
        string tth;
        if(!cmd.getParam("TR", 1, tth))
            return; // nothing to identify a file?

        string size;
        if(!cmd.getParam("SI", 1, size))
            return; // no file size?

        string partial;
        cmd.getParam("PF", 1, partial);

        addSource(TTHValue(tth), node, Util::toInt64(size), partial == "1");

        // send response
        AdcCommand res(AdcCommand::SEV_SUCCESS, AdcCommand::SUCCESS, "File published", AdcCommand::TYPE_UDP);
        res.addParam("FC", "PUB");
        res.addParam("TR", tth);
        DHT::getInstance()->send(res, node->getIdentity().getIp(), node->getIdentity().getUdpPort(), node->getUser()->getCID(), node->getUdpKey());
    }
Ejemplo n.º 30
0
void
bullet::ColliderDebug::targetAddedHandler(AbstractComponent::Ptr, Node::Ptr target)
{
	if (targets().size() > 1)
		throw std::logic_error("Collider debugging component cannot be added twice.");

	_addedSlot = target->added()->connect(std::bind(
		&ColliderDebug::addedHandler,
		std::static_pointer_cast<ColliderDebug>(shared_from_this()),
		std::placeholders::_1,
		std::placeholders::_2,
		std::placeholders::_3
	));

	_removedSlot = target->removed()->connect(std::bind(
		&ColliderDebug::removedHandler,
		std::static_pointer_cast<ColliderDebug>(shared_from_this()),
		std::placeholders::_1,
		std::placeholders::_2,
		std::placeholders::_3
	));
}