std::string FunctionReference::getDebugName() {
    if (getNamespace().size() > 0) {
        return getNamespace() + "." + getName();
    } else {
        return getName();
    }
}
  void IndexArticle::readEntriesB()
  {
    try
    {
      zim::size_type categoryCount[4];
      zim::Blob b = getData();
      ptrstream data(const_cast<char*>(b.data()), const_cast<char*>(b.end()));
      for (unsigned c = 0; c < 4; ++c)
        categoryCount[c] = getSizeValue(data);

      for (unsigned c = 0; c < 4; ++c)
      {
        log_debug("read " << categoryCount[c] << " entries for category " << c);
        for (unsigned n = 0; n < categoryCount[c]; ++n)
        {
          Entry entry;
          entry.index = getSizeValue(data);
          if (getNamespace() == 'X')
            entry.pos = getNamespace() ? getSizeValue(data) : 0;
          entries[c].push_back(entry);
        }
      }
    }
    catch (const Eof&)
    {
      log_error("end of file when reading index entries for article " << getTitle());
      return;
    }
  }
Exemple #3
0
Status ClusterAggregate::aggPassthrough(OperationContext* txn,
                                        const Namespaces& namespaces,
                                        std::shared_ptr<DBConfig> conf,
                                        BSONObj cmdObj,
                                        BSONObjBuilder* out,
                                        int queryOptions) {
    // Temporary hack. See comment on declaration for details.
    auto shardStatus = grid.shardRegistry()->getShard(txn, conf->getPrimaryId());
    if (!shardStatus.isOK()) {
        return shardStatus.getStatus();
    }

    ShardConnection conn(shardStatus.getValue()->getConnString(), "");
    BSONObj result = aggRunCommand(conn.get(), namespaces, cmdObj, queryOptions);
    conn.done();

    // First append the properly constructed writeConcernError. It will then be skipped
    // in appendElementsUnique.
    if (auto wcErrorElem = result["writeConcernError"]) {
        appendWriteConcernErrorToCmdResponse(shardStatus.getValue()->getId(), wcErrorElem, *out);
    }

    out->appendElementsUnique(result);

    BSONObj responseObj = out->asTempObj();
    if (ResolvedView::isResolvedViewErrorResponse(responseObj)) {
        auto resolvedView = ResolvedView::fromBSON(responseObj);

        auto request = AggregationRequest::parseFromBSON(resolvedView.getNamespace(), cmdObj);
        if (!request.isOK()) {
            out->resetToEmpty();
            return request.getStatus();
        }

        auto aggCmd = resolvedView.asExpandedViewAggregation(request.getValue());
        if (!aggCmd.isOK()) {
            out->resetToEmpty();
            return aggCmd.getStatus();
        }

        out->resetToEmpty();

        // We pass both the underlying collection namespace and the view namespace here. The
        // underlying collection namespace is used to execute the aggregation on mongoD. Any cursor
        // returned will be registered under the view namespace so that subsequent getMore and
        // killCursors calls against the view have access.
        Namespaces nsStruct;
        nsStruct.requestedNss = namespaces.requestedNss;
        nsStruct.executionNss = resolvedView.getNamespace();
        return ClusterAggregate::runAggregate(txn, nsStruct, aggCmd.getValue(), queryOptions, out);
    }

    return getStatusFromCommandResult(result);
}
Exemple #4
0
    bool Multiname::matches(const Multiname* qname) const
    {
        // For attributes (XML::getprop page 12)
        //if (((n.[[Name]].localName == "*") || (n.[[Name]].localName == a.[[Name]].localName)) &&
        //  ((n.[[Name]].uri == nulll) || (n.[[Name]].uri == a.[[Name]].uri)))

        // For regular element props (XML::getprop page 12)
        //  if (n.localName = "*" OR m2 and (m2.localName == n.localName)
        //  and (!n.uri) or (m2) and (n.uri == m2.uri)))

        //Stringp n1 = core->string(this->name);

        if (qname)
        {
            //Stringp n2 = core->string(m2->name);

            if (this->isAttr() != qname->isAttr())
                return false;
        }

        // An anyName that is not qualified matches all properties
        if (this->isAnyName() && !this->isQName())
            return true;

        // Not an anyName, if m2 is valid, verify names are identical
        if (!this->isAnyName() && qname && (this->name != qname->getName()))
            return false;

        if (!qname)
            return false;

        if (this->isAnyNamespace())
            return true;

        // find a matching namespace between m2 and this
        // if no match return false
        Stringp u2 = qname->getNamespace()->getURI();
        uint8 type2 = (uint8)(qname->getNamespace()->getType());
        //Stringp s2 = core->string(u2);

        for (int i = 0; i < this->namespaceCount(); i++)
        {
            // We'd like to just compare namespace objects but we need
            // to check URIs since two namespaces with different prefixes
            // are considered a match
            Stringp u1 = getNamespace(i)->getURI();
            uint8 type1 = (uint8)(getNamespace(i)->getType());
            //Stringp s1 = core->string(u1);
            if (u1 == u2 && type1 == type2)
                return true;
        }

        return false;
    }
//#ifdef AVMPLUS_VERBOSE
	// Made available in non-AVMPLUS_VERBOSE builds for describeType
	Stringp Multiname::format(AvmCore* core , MultiFormat form) const
	{
		Stringp attr = this->isAttr() ? core->newString("@") : (Stringp)core->kEmptyString;
		Stringp name = this->isAnyName() 
			? core->newString("*") 
			: (this->isRtname()
				? core->newString("[]")
				: getName());

		if (isAnyNamespace())
		{
			return core->concatStrings(attr, core->concatStrings(core->newString("*::"), name));
		}
		else if (isRtns())
		{
			return core->concatStrings(attr, core->concatStrings(core->newString("[]::"), name));
		}
		else if (namespaceCount() == 1 && isQName()) 
		{
			return format(core, getNamespace(), core->concatStrings(attr,name), false, false);
		}
		else
		{
			// various switches
			bool showNs = (form == MULTI_FORMAT_FULL) || (form == MULTI_FORMAT_NS_ONLY);
			bool showName = (form == MULTI_FORMAT_FULL) || (form == MULTI_FORMAT_NAME_ONLY);
			bool showBrackets = (form == MULTI_FORMAT_FULL);
			Stringp s = attr;
			if (showNs)
			{
				if (showBrackets)
					s = core->concatStrings(s, core->newString("{"));

				for (int i=0,n=namespaceCount(); i < n; i++) 
				{			
					if (getNamespace(i)==core->publicNamespace)
						s = core->concatStrings(s, core->newString("public"));
					else
						s = core->concatStrings(s, getNamespace(i)->getURI());
					if (i+1 < n)
						s = core->concatStrings(s, core->newString(","));
				}

				if (showBrackets)
					s = core->concatStrings(s, core->newString("}::"));
			}

			if (showName)
				s = core->concatStrings(s, name);
			return s;
		}
	}
Status checkAuthForWriteCommand(AuthorizationSession* authzSession,
                                BatchedCommandRequest::BatchType cmdType,
                                const OpMsgRequest& request) {
    std::vector<Privilege> privileges;
    ActionSet actionsOnCommandNSS;

    if (shouldBypassDocumentValidationForCommand(request.body)) {
        actionsOnCommandNSS.addAction(ActionType::bypassDocumentValidation);
    }

    NamespaceString cmdNSS;
    if (cmdType == BatchedCommandRequest::BatchType_Insert) {
        auto op = Insert::parse(IDLParserErrorContext("insert"), request);
        cmdNSS = op.getNamespace();
        if (!op.getNamespace().isSystemDotIndexes()) {
            actionsOnCommandNSS.addAction(ActionType::insert);
        } else {
            // Special-case indexes until we have a command
            const auto swNssToIndex = getIndexedNss(op.getDocuments());
            if (!swNssToIndex.isOK()) {
                return swNssToIndex.getStatus();
            }

            const auto& nssToIndex = swNssToIndex.getValue();
            privileges.push_back(
                Privilege(ResourcePattern::forExactNamespace(nssToIndex), ActionType::createIndex));
        }
    } else if (cmdType == BatchedCommandRequest::BatchType_Update) {
        auto op = Update::parse(IDLParserErrorContext("update"), request);
        cmdNSS = op.getNamespace();
        actionsOnCommandNSS.addAction(ActionType::update);

        // Upsert also requires insert privs
        if (containsUpserts(op.getUpdates())) {
            actionsOnCommandNSS.addAction(ActionType::insert);
        }
    } else {
        fassert(17251, cmdType == BatchedCommandRequest::BatchType_Delete);
        auto op = Delete::parse(IDLParserErrorContext("delete"), request);
        cmdNSS = op.getNamespace();
        actionsOnCommandNSS.addAction(ActionType::remove);
    }

    if (!actionsOnCommandNSS.empty()) {
        privileges.emplace_back(ResourcePattern::forExactNamespace(cmdNSS), actionsOnCommandNSS);
    }

    if (authzSession->isAuthorizedForPrivileges(privileges))
        return Status::OK();

    return Status(ErrorCodes::Unauthorized, "unauthorized");
}
bool Material::parseTechnique(Properties* techniqueProperties)
{
    auto technique = Technique::create(this);
    _techniques.pushBack(technique);

    // first one is the default one
    if (!_currentTechnique)
        _currentTechnique = technique;

    // name
    technique->setName(techniqueProperties->getId());


    // passes
    auto space = techniqueProperties->getNextNamespace();
    while (space)
    {
        const char* name = space->getNamespace();
        if (strcmp(name, "pass") == 0)
        {
            parsePass(technique, space);
        }
        else if (strcmp(name, "renderState") == 0)
        {
            parseRenderState(this, space);
        }

        space = techniqueProperties->getNextNamespace();
    }

    return true;
}
bool Material::parsePass(Technique* technique, Properties* passProperties)
{
    auto pass = Pass::create(technique);
    technique->addPass(pass);

    // Pass can have 3 different namespaces:
    //  - one or more "sampler"
    //  - one "renderState"
    //  - one "shader"

    auto space = passProperties->getNextNamespace();
    while (space)
    {
        const char* name = space->getNamespace();
        if (strcmp(name, "shader") == 0)
            parseShader(pass, space);
        else if (strcmp(name, "renderState") == 0)
            parseRenderState(pass, space);
        else {
            CCASSERT(false, "Invalid namespace");
            return false;
        }

        space = passProperties->getNextNamespace();
    }

    return true;
}
Exemple #9
0
int NamespaceAddTarget(namespaceref ns, vref name, int index)
{
    int existingFunction = NamespaceAddFunction(ns, name, index);
    if (existingFunction >= 0)
    {
        return existingFunction;
    }
    existingFunction = IntHashMapSet(&getNamespace(ns)->targetIndex, intFromRef(name), index + 1);
    assert(!existingFunction);
    return -1;
}
    void
    startVolume()
    {
        ASSERT(not vol_);
        startVolManager();
        vol_ = newVolume("volume1",
			 getNamespace());
        ASSERT(vol_);
        dStore_ = vol_->getDataStore();
        ASSERT(dStore_);

    }
Exemple #11
0
void NamespaceDispose(void)
{
    Namespace *ns;
    const Namespace *limit;

    if (initialised)
    {
        limit = (Namespace*)BVGetPointer(&namespaceData, BVSize(&namespaceData));
        for (ns = getNamespace(1); ns < limit; ns++)
        {
            disposeNamespace(ns);
        }
        BVDispose(&namespaceData);
        IntHashMapDispose(&nameNamespace);
    }
}
Exemple #12
0
bool SFXSource::_setStatus( SFXStatus status )
{
   if ( mStatus == status )
      return false;

   mStatus = status;

   // Do the callback if we have it.

   const char* statusString = SFXStatusToString( mStatus );
   if ( mStatusCallback && mStatusCallback[0] )
      Con::executef( mStatusCallback, getIdString(), statusString );
   else if ( getNamespace() )
      Con::executef( this, "onStatusChange", statusString );

   return true;
}
Exemple #13
0
namespaceref NamespaceCreate(vref name)
{
    Namespace *entry;
    namespaceref ref =
        refFromSize(BVSize(&namespaceData) / sizeof(Namespace));

    BVGrow(&namespaceData, sizeof(Namespace));
    entry = getNamespace(ref);
    entry->name = name;
    IntHashMapInit(&entry->namespaces, 1);
    IntHashMapInit(&entry->fieldIndex, 32);
    IntHashMapInit(&entry->functionIndex, 32);
    IntHashMapInit(&entry->targetIndex, 32);
    if (name)
    {
        IntHashMapAdd(&nameNamespace, intFromRef(name), intFromRef(ref));
    }
    return ref;
}
bool Material::parseShader(Pass* pass, Properties* shaderProperties)
{
    // vertexShader
    const char* vertShader = getOptionalString(shaderProperties, "vertexShader", nullptr);

    // fragmentShader
    const char* fragShader = getOptionalString(shaderProperties, "fragmentShader", nullptr);

    // compileTimeDefines
    const char* compileTimeDefines = getOptionalString(shaderProperties, "defines", "");

    if (vertShader && fragShader)
    {
        auto glProgramState = GLProgramState::getOrCreateWithShaders(vertShader, fragShader, compileTimeDefines);
        pass->setGLProgramState(glProgramState);

        // Parse uniforms only if the GLProgramState was created
        auto property = shaderProperties->getNextProperty();
        while (property)
        {
            if (isValidUniform(property))
            {
                parseUniform(glProgramState, shaderProperties, property);
            }

            property = shaderProperties->getNextProperty();
        }

        auto space = shaderProperties->getNextNamespace();
        while (space)
        {
            const char* name = space->getNamespace();
            if (strcmp(name, "sampler") == 0)
            {
                parseSampler(glProgramState, space);
            }
            space = shaderProperties->getNextNamespace();
        }
    }

    return true;
}
    void
    truncate_sco_in_cache(SCO sconame,
                          uint64_t size,
                          bool must_exist = true)
    {
        CachedSCOPtr sco =
            VolManager::get()->getSCOCache()->findSCO(getNamespace(),
                                                      sconame);
        if (must_exist)
        {
            ASSERT_TRUE(sco != nullptr);
        }

        if (sco)
        {
            ASSERT_TRUE(fs::exists(sco->path()));
            FileUtils::truncate(sco->path(),
                                size);
        }
    }
bool Material::parseProperties(Properties* materialProperties)
{
    setName(materialProperties->getId());
    auto space = materialProperties->getNextNamespace();
    while (space)
    {
        const char* name = space->getNamespace();
        if (strcmp(name, "technique") == 0)
        {
            parseTechnique(space);
        }
        else if (strcmp(name, "renderState") == 0)
        {
            parseRenderState(this, space);
        }

        space = materialProperties->getNextNamespace();

    }
    return true;
}
Exemple #17
0
void CSVWorld::GenericCreator::updateNamespace()
{
    std::string namespace_ = getNamespace();

    mValidator->setNamespace (namespace_);

    int index = mId->text().indexOf ("::");

    if (index==-1)
    {
        // no namespace in old text
        mId->setText (QString::fromUtf8 (namespace_.c_str()) + mId->text());
    }
    else
    {
        std::string oldNamespace =
            Misc::StringUtils::lowerCase (mId->text().left (index).toUtf8().constData());

        if (oldNamespace=="project" || oldNamespace=="session")
            mId->setText (QString::fromUtf8 (namespace_.c_str()) + mId->text().mid (index+2));
    }
}
Exemple #18
0
XSNamespaceItem *XSElementDeclaration::getNamespaceItem() 
{
    return fXSModel->getNamespaceItem(getNamespace());
}
XSNamespaceItem *XSAttributeDeclaration::getNamespaceItem() 
{
    return fXSModel->getNamespaceItem(getNamespace());
}
Exemple #20
0
int NamespaceAddFunction(namespaceref ns, vref name, int index)
{
    return IntHashMapSet(&getNamespace(ns)->functionIndex, intFromRef(name), index + 1) - 1;
}
		void startElement(
			const XMLCh* namespaceURI, 
			const XMLCh* lName, 
			const XMLCh* qName,
			const xercesc::Attributes& attrs)
		{
			std::shared_ptr<Fragment> fragment;

			if (namespaceURI == XS(XMLConstants::XMLSchemaNamespace)) 
			{
				if (lName == L"group")
				{
					fragment = std::make_shared<SchemaGroupCompositor>();
				} 
				else if (lName == L"all")
				{
					fragment = std::make_shared<SchemaAllCompositor>();
				} 
				else if (lName == L"choice")
				{
					fragment = std::make_shared<SchemaChoiceCompositor>();
				} 
				else if (lName == L"sequence")
				{
					fragment = std::make_shared<SchemaSequenceCompositor>();
				} 
				else if (lName == L"complexType")
				{
					fragment = std::make_shared<TypeDeclaration>();
				} 
				else if (lName == L"simpleType")
				{
					fragment = std::make_shared<SimpleTypeDeclaration>();
				} 
				else if (lName == L"attribute")
				{
					fragment = std::make_shared<AttributeDeclaration>();
				} 
				else if (lName == L"attributeGroup")
				{
					fragment = std::make_shared<AttributeGroupDeclaration>();
				} 
				else if (lName == L"schema")
				{
					fragment = std::make_shared<Schema>();
					setXSModel(constructXSModel());
					setTargetNamespace(std::shared_ptr<const XMLCh>(attrs.getValue(L"targetNamespace")));
				} 
				else if (lName == L"element")
				{
					auto elementName = std::shared_ptr<const XMLCh>(attrs.getValue(L"name"));

					if (!getXSModel().get()) 
					{
						throw new XBRLException("An XML Schema element declaration was found outside of an XML Schema.");
					}

					auto targetNamespace = getTargetNamespace(); 
					if (!targetNamespace.get()) 
					{
						throw new XBRLException("An XML Schema element was found without a target namespace.");
					}

					// Find the XS model element declaration for the element that has been started - if one can be found
					std::shared_ptr<XSElementDeclaration> declaration;

					// Handle anonymous schemas first - these are the tough case
					if (targetNamespace.get())
					{
						// Get the list of namespaces declared in the model
						auto nsItemList = std::shared_ptr<XSNamespaceItemList>(getXSModel()->getNamespaceItems());

						// For each namespace ...
						for (XMLSize_t i=0; i < nsItemList->size(); ++i) 
						{
							auto nsItem = std::shared_ptr<XSNamespaceItem>(nsItemList->elementAt(i));

							// Get a candidate element declaration if one exists
							auto candidateDeclaration = std::shared_ptr<XSElementDeclaration>(nsItem->getElementDeclaration(elementName.get()));


							if (candidateDeclaration.get()) 
							{
								// Get the URIs of the documents that were used to create elements in this namespace
								auto locations = std::shared_ptr<const StringList>(nsItem->getDocumentLocations());

								// Check to see if the current document URI is one of those documents and if so, the candidate could be good
								for (XMLSize_t j=0; j < locations->size(); ++j) 
								{
									auto location = locations->elementAt(j);
									if (to_string(location) == contentHandler->getURI().toString()) 
									{
										// Throw an exception if we find two feasible candidate element declarations in the Schema model
										if (declaration.get()) throw new XBRLException("Potentially ambiguous anonymous Schema problem.");
										declaration = candidateDeclaration;
									}
								}
							}
						}

						if (!declaration.get()) throw new XBRLException("An element declaration was found that could not be handled.");

						// Handle the easy case where the schema specifies its target namespace
					} 
					else if (elementName.get()) 
					{

						declaration = 
							std::shared_ptr<XSElementDeclaration>(
								getXSModel()->getElementDeclaration(elementName.get(), 
								getTargetNamespace().get()));
					}

					// Determine what substitution groups the element is in - if any.
					if (declaration.get()) 
					{
						auto sgDeclaration = std::shared_ptr<XSElementDeclaration>(declaration->getSubstitutionGroupAffiliation());
						while (sgDeclaration.get()) 
						{
							if (to_string(sgDeclaration->getNamespace()) == XMLConstants::XBRL21Namespace)
							{
								if (sgDeclaration->getName() == L"item")
								{
									fragment = std::shared_ptr<Concept>();
									break;
								} 
								else if (sgDeclaration->getName() == L"tuple")
								{
									fragment = std::shared_ptr<Concept>();
									break;
								}
							}

							if (to_string(sgDeclaration->getNamespace()) == XMLConstants::XBRL21LinkNamespace)
							{
								//if (sgDeclaration->getName() == L"part")
								//	fragment = std::shared_ptr<ReferencePartDeclaration>();
								break;
							}
							sgDeclaration = 
								std::shared_ptr<XSElementDeclaration>(sgDeclaration->getSubstitutionGroupAffiliation());
						}
					}

					if (!fragment.get()) 
					{
						fragment = std::shared_ptr<ElementDeclaration>();
					}
				}

				if (fragment.get()) 
				{
					outer.lock()->processFragment(fragment, attrs);
				}
			}
		}
Exemple #22
0
QString
vleSmDT::getData()
{
    QString tpl = "/**\n"                                               \
        "  * @file {{classname}}.cpp\n"                                 \
        "  * @author ...\n"                                             \
        "  * ...\n"                                                     \
        "  */\n\n"                                                      \
        "/*\n"                                                          \
        " * @@tagdynamic@@\n"                                           \
        " * @@tagdepends: vle.discrete-time @@endtagdepends\n"          \
        "*/\n\n"                                                        \
        "#include <vle/DiscreteTimeDbg.hpp>\n"                          \
        "#include <vle/devs/DynamicsDbg.hpp>\n\n"                       \
        "{{includes}}"                                                  \
        "namespace vd = vle::devs;\n\n"                                 \
        "namespace vv = vle::value;\n\n"                                \
        "namespace vle {\n"                                             \
        "namespace discrete_time {\n"                                   \
        "namespace {{namespace}} {\n\n"                                 \
        "class {{classname}} : public DiscreteTimeDyn\n"                \
        "{\n"                                                           \
        "public:\n"                                                     \
        "{{classname}}(\n"                                              \
        "    const vd::DynamicsInit& init,\n"                           \
        "    const vd::InitEventList& evts)\n"                          \
        "        : DiscreteTimeDyn(init, evts)\n"                       \
        "{\n"                                                           \
        "{{for i in var}}"                                              \
        "    {{var^i}}.init(this, \"{{var^i}}\", evts);\n"              \
        "{{end for}}"                                                   \
        "{{for i in init_value_var}}"                                   \
        "    {{init_value_var^i}}.init_value({{init_value_val^i}});\n"  \
        "{{end for}}"                                                   \
        "{{construct}}"                                                 \
        "\n"                                                            \
        "}\n"                                                           \
        "\n"                                                            \
        "virtual ~{{classname}}()\n"                                    \
        "{}\n"                                                          \
        "\n"                                                            \
        "void compute(const vle::devs::Time& t)\n"                      \
        "{\n"                                                           \
        "{{compute}}"                                                   \
        "}\n"                                                           \
        "\n"                                                            \
        "{{for i in var}}"                                              \
        "    Var {{var^i}};\n"                                          \
        "{{end for}}"                                                   \
        "{{userSection}}"                                               \
        "};\n\n"                                                        \
        "} // namespace {{namespace}}\n"                                \
        "} // namespace discrete_time\n"                                \
        "} // namespace vle\n\n"                                        \
        "DECLARE_DYNAMICS("                                             \
        "vle::discrete_time::{{namespace}}::{{classname}})\n\n";


    vle::utils::Template vleTpl(tpl.toStdString());
    vleTpl.stringSymbol().append("classname", getClassName().toStdString());
    vleTpl.stringSymbol().append("namespace", getNamespace().toStdString());

    vleTpl.listSymbol().append("var");
    vleTpl.listSymbol().append("init_value_var");
    vleTpl.listSymbol().append("init_value_val");


    QDomNodeList variablesXml = variablesFromDoc();
    for (int i = 0; i < variablesXml.length(); i++) {
        QDomNode variable = variablesXml.item(i);
        QString varName = variable.attributes().namedItem("name").nodeValue();
        vle::value::Value* val = getInitialValue(varName);
        if (val) {
            vleTpl.listSymbol().append("init_value_var", varName.toStdString());
            vleTpl.listSymbol().append("init_value_val", val->writeToString());
            delete val;
        }

        vleTpl.listSymbol().append("var", varName.toStdString());


    }

    vleTpl.stringSymbol().append("includes", "");
    vleTpl.stringSymbol().append("compute", getComputeBody().toStdString());
    vleTpl.stringSymbol().append("construct","");
    vleTpl.stringSymbol().append("userSection","");

    std::ostringstream out;
    vleTpl.process(out);

    return QString(out.str().c_str());
}
XSNamespaceItem *XSModelGroupDefinition::getNamespaceItem() 
{
    return fXSModel->getNamespaceItem(getNamespace());
}
Exemple #24
0
int NamespaceGetTarget(namespaceref ns, vref name)
{
    return IntHashMapGet(&getNamespace(ns)->targetIndex, intFromRef(name)) - 1;
}
Exemple #25
0
int NamespaceGetField(namespaceref ns, vref name)
{
    return IntHashMapGet(&getNamespace(ns)->fieldIndex, intFromRef(name)) - 1;
}
Exemple #26
0
void RespondElement::enterElement(const Arabica::DOM::Element<std::string>& node) {
	// try to get the request id
	if (!HAS_ATTR(node, "to")) {
		LOG(ERROR) << "Respond element requires to attribute";
		return;
	}
	if (HAS_ATTR(node, "to") && !_interpreter->getDataModel()) {
		LOG(ERROR) << "Respond element with to requires datamodel";
		return;
	}
	std::string requestId = _interpreter->getDataModel().evalAsString(ATTR(node, "to"));

	// try to get the request object
	InterpreterHTTPServlet* servlet = _interpreter->getHTTPServlet();
	tthread::lock_guard<tthread::recursive_mutex> lock(servlet->getMutex());

	if (servlet->getRequests().find(requestId) == servlet->getRequests().end()) {
		LOG(ERROR) << "No matching HTTP request for respond element";
		return;
	}

	assert(servlet->getRequests().find(requestId) != servlet->getRequests().end());
	HTTPServer::Request httpReq = servlet->getRequests()[requestId];
	assert(httpReq.evhttpReq != NULL);
	HTTPServer::Reply httpReply(httpReq);
	servlet->getRequests().erase(requestId);

	// get the status or default to 200
	std::string statusStr = (HAS_ATTR(node, "status") ? ATTR(node, "status") : "200");
	if (!isNumeric(statusStr.c_str(), 10)) {
		LOG(ERROR) << "Respond element with non-numeric status " << statusStr;
		return;
	}
	httpReply.status = strTo<int>(statusStr);;

	// extract the content
	Arabica::XPath::NodeSet<std::string> contents = InterpreterImpl::filterChildElements(_interpreter->getNameSpaceInfo().getXMLPrefixForNS(getNamespace()) + "content", node);
	if (contents.size() > 0) {
		Arabica::DOM::Element<std::string> contentElem = Arabica::DOM::Element<std::string>(contents[0]);
		if (HAS_ATTR(contentElem, "expr")) { // -- content is evaluated string from datamodel ------
			if (_interpreter->getDataModel()) {
				try {
					Data contentData = _interpreter->getDataModel().getStringAsData(ATTR(contentElem, "expr"));
					if (contentData.atom.length() > 0) {
						httpReply.content = contentData.atom;
						httpReply.headers["Content-Type"] = "text/plain";
					} else if (contentData.binary) {
						httpReply.content = std::string(contentData.binary.getData(), contentData.binary.getSize());
						httpReply.headers["Content-Type"] = contentData.binary.getMimeType();
					} else if (contentData.node) {
						std::stringstream ss;
						ss << contentData.node;
						httpReply.content = ss.str();;
						httpReply.headers["Content-Type"] = "application/xml";
					} else {
						httpReply.content = Data::toJSON(contentData);
						httpReply.headers["Content-Type"] = "application/json";
					}
				} catch (Event e) {
					LOG(ERROR) << "Syntax error with expr in content child of Respond element:" << std::endl << e << std::endl;
					return;
				}
			} else {
				LOG(ERROR) << "content element has expr attribute but no datamodel is specified.";
				return;
			}
		} else if (HAS_ATTR(contentElem, "file") || HAS_ATTR(contentElem, "fileexpr")) { // -- content is from file ------
			URL file;
			if (HAS_ATTR(contentElem, "fileexpr")) {
				if (_interpreter->getDataModel()) {
					try {
						file = "file://" + _interpreter->getDataModel().evalAsString(ATTR(contentElem, "fileexpr"));
					} catch (Event e) {
						LOG(ERROR) << "Syntax error with fileexpr in content child of Respond element:" << std::endl << e << std::endl;
						return;
					}
				}
			} else {
				file = "file://" + ATTR(contentElem, "fileexpr");
			}
			if (file) {
				httpReply.content = file.getInContent();
				size_t lastDot;
				if ((lastDot = file.path().find_last_of(".")) != std::string::npos) {
					std::string extension = file.path().substr(lastDot + 1);
					std::string mimeType = URL::getMimeType(extension);
					if (mimeType.length() > 0) {
						httpReply.headers["Content-Type"] = mimeType;
					}
				}
			}
		} else if (contents[0].hasChildNodes()) {  // -- content embedded as child nodes ------
			httpReply.content = contents[0].getFirstChild().getNodeValue();
		} else {
			LOG(ERROR) << "content element does not specify any content.";
			return;
		}
	}

	// process headers
	Arabica::XPath::NodeSet<std::string> headers = InterpreterImpl::filterChildElements(_interpreter->getNameSpaceInfo().getXMLPrefixForNS(getNamespace()) + "header", node);
	for (int i = 0; i < headers.size(); i++) {
		Arabica::DOM::Element<std::string> headerElem = Arabica::DOM::Element<std::string>(headers[i]);

		std::string name;
		if (HAS_ATTR(headerElem, "name")) {
			name = ATTR(headerElem, "name");
		} else if(HAS_ATTR(headerElem, "nameexpr")) {
			if (_interpreter->getDataModel()) {
				try {
					name = _interpreter->getDataModel().evalAsString(ATTR(headerElem, "nameexpr"));
				} catch (Event e) {
					LOG(ERROR) << "Syntax error with nameexpr in header child of Respond element:" << std::endl << e << std::endl;
					return;
				}
			} else {
				LOG(ERROR) << "header element has nameexpr attribute but no datamodel is specified.";
				return;
			}
		} else {
			LOG(ERROR) << "header element has no name or nameexpr attribute.";
			return;
		}

		std::string value;
		if (HAS_ATTR(headerElem, "value")) {
			value = ATTR(headerElem, "value");
		} else if(HAS_ATTR(headerElem, "valueexpr")) {
			if (_interpreter->getDataModel()) {
				try {
					value = _interpreter->getDataModel().evalAsString(ATTR(headerElem, "valueexpr"));
				} catch (Event e) {
					LOG(ERROR) << "Syntax error with valueexpr in header child of Respond element:" << std::endl << e << std::endl;
					return;
				}
			} else {
				LOG(ERROR) << "header element has valueexpr attribute but no datamodel is specified.";
				return;
			}
		} else {
			LOG(ERROR) << "header element has no value or valueexpr attribute.";
			return;
		}

		httpReply.headers[name] = value;
	}

	// send the reply
	HTTPServer::reply(httpReply);
	servlet->getRequests().erase(requestId);
}
void LocalNode::listenLocalNetwork()
{
    NodeNetwork::setupLocalNode(getNamespace(), this->mpImpl);
}
Exemple #28
0
int NamespaceGetFunction(namespaceref ns, vref name)
{
    return IntHashMapGet(&getNamespace(ns)->functionIndex, intFromRef(name)) - 1;
}
Exemple #29
0
void Properties::resolveInheritance(const char* id)
{
    // Namespaces can be defined like so:
    // "name id : parentID { }"
    // This method merges data from the parent namespace into the child.

    // Get a top-level namespace.
    Properties* derived;
    if (id)
    {
        derived = getNamespace(id);
    }
    else
    {
        derived = getNextNamespace();
    }
    while (derived)
    {
        // If the namespace has a parent ID, find the parent.
        if (!derived->_parentID.empty())
        {
            Properties* parent = getNamespace(derived->_parentID.c_str());
            if (parent)
            {
                resolveInheritance(parent->getId());

                // Copy the child.
                Properties* overrides = new (std::nothrow) Properties(*derived);

                // Delete the child's data.
                for (size_t i = 0, count = derived->_namespaces.size(); i < count; i++)
                {
                    CC_SAFE_DELETE(derived->_namespaces[i]);
                }

                // Copy data from the parent into the child.
                derived->_properties = parent->_properties;
                derived->_namespaces = std::vector<Properties*>();
                std::vector<Properties*>::const_iterator itt;
                for (const auto space: parent->_namespaces)
                {
                    derived->_namespaces.push_back(new (std::nothrow) Properties(*space));
                }
                derived->rewind();

                // Take the original copy of the child and override the data copied from the parent.
                derived->mergeWith(overrides);

                // Delete the child copy.
                CC_SAFE_DELETE(overrides);
            }
        }

        // Resolve inheritance within this namespace.
        derived->resolveInheritance();

        // Get the next top-level namespace and check again.
        if (!id)
        {
            derived = getNextNamespace();
        }
        else
        {
            derived = NULL;
        }
    }
}
XSNamespaceItem *XSComplexTypeDefinition::getNamespaceItem() 
{
    return fXSModel->getNamespaceItem(getNamespace());
}