コード例 #1
0
ファイル: TopologyJSON.cpp プロジェクト: johnson325/pothos
/***********************************************************************
 * block factory - make blocks from JSON object
 **********************************************************************/
static Pothos::Proxy makeBlock(
    const Pothos::Proxy &registry,
    const Pothos::Proxy &evaluator,
    const Poco::JSON::Object::Ptr &blockObj)
{
    const auto id = blockObj->getValue<std::string>("id");

    if (not blockObj->has("path")) throw Pothos::DataFormatException(
        "Pothos::Topology::make()", "blocks["+id+"] missing 'path' field");
    const auto path = blockObj->getValue<std::string>("path");

    //load up the constructor args
    Poco::JSON::Array::Ptr argsArray;
    if (blockObj->isArray("args")) argsArray = blockObj->getArray("args");
    const auto ctorArgs = evalArgsArray(evaluator, argsArray);

    //create the block
    auto block = registry.getHandle()->call(path, ctorArgs.data(), ctorArgs.size());

    //make the calls
    Poco::JSON::Array::Ptr callsArray;
    if (blockObj->isArray("calls")) callsArray = blockObj->getArray("calls");
    if (callsArray) for (size_t i = 0; i < callsArray->size(); i++)
    {
        const auto callArray = callsArray->getArray(i);
        auto name = callArray->getElement<std::string>(0);
        const auto callArgs = evalArgsArray(evaluator, callArray, 1/*offset*/);
        block.getHandle()->call(name, callArgs.data(), callArgs.size());
    }

    return block;
}
コード例 #2
0
ファイル: main.cpp プロジェクト: shuchuangtech/Shuchuang
void updateTasksList()
{
	printf("updateTasksList()\n");
	tasksNum = task_manager->getTasksNumber();
	if(tasksNum > 0)
	{
		Poco::JSON::Object::Ptr pObj = new Poco::JSON::Object;
		task_manager->getTasks(pObj);
		Poco::DynamicStruct ds = *pObj;
		printf("ds:%s\n", ds.toString().c_str());
		if(pObj->has("tasks"))
			printf("pObj has tasks\n");
		if(pObj->isArray("tasks"))
			printf("pObj is array tasks\n");
		Poco::JSON::Array::Ptr pArray = pObj->getArray("tasks");
		printf("tasksNum:%d, array size:%d\n", tasksNum, pArray->size());
		for(int i = 0; i < tasksNum; i++)
		{
			memset(pTask[i], 0, sizeof(TaskInfo));
			Poco::Dynamic::Var var = pArray->get(i);
			Poco::DynamicStruct dss = var.extract<Poco::DynamicStruct>();
			pTask[i]->id = (Poco::Int64)dss["id"].extract<Poco::Int64>();
			pTask[i]->option = dss["option"].extract<int>();
			pTask[i]->hour = dss["hour"].extract<int>();
			pTask[i]->minute = dss["minute"].extract<int>();
			pTask[i]->weekday = dss["weekday"].extract<int>();
		}
	}
}
コード例 #3
0
void Controller::searchSimilarRequest(std::map<std::string, std::string>& params, const Poco::Dynamic::Var& request) {
    Record record;
    vector<uint8_t>* image_data = NULL;
    int count = 10;
    
    if (params.count("blockHash")) {
        record.getHashes()[BlockHash] = str2bin(params["blockHash"]);
    }
    if (params.count("dHash")) {
        record.getHashes()[DHash] = str2bin(params["dHash"]);
    }
    if (params.count("gaussDHash")) {
        record.getHashes()[GaussDHash] = str2bin(params["gaussDHash"]);
    }
    if (params.count("gauss2DHash")) {
        record.getHashes()[Gauss2DHash] = str2bin(params["gauss2DHash"]);
    }
    if (params.count("gaussBlockHash")) {
        record.getHashes()[GaussBlockHash] = str2bin(params["gaussBlockHash"]);
    }
    if (params.count("url")) {
        image_data = Image::fromUrl(params["url"]);
    }
    if (params.count("count")) {
        count = atoi(params["count"].c_str());
    }
    
    if (!request.isEmpty()) {
        Poco::JSON::Object::Ptr json = request.extract<Poco::JSON::Object::Ptr>();
        if (!image_data && json->has("image_base64")) {
            image_data = Image::fromBase64(json->getValue<string>("image_base64"));
        }
        if (!image_data && json->has("image_url")) {
            image_data = Image::fromUrl(json->getValue<string>("image_url"));
        }
    }
    
    if (image_data) {
        HashAlgorithmManager::getInstance().attachSimilarHashes(record, image_data);
        delete image_data;
    }
    
    appio::print_ok(HashManager::getInstance().searchSimilar(record, count));
}
コード例 #4
0
void AffinityZoneEditor::loadFromConfig(const Poco::JSON::Object::Ptr &config)
{
    if (config->has("color"))
    {
        auto color = QString::fromStdString(config->getValue<std::string>("color"));
        _colorPicker->blockSignals(true);
        _colorPicker->setCurrentColor(QColor(color));
        _colorPicker->blockSignals(false);
    }
    if (config->has("hostUri"))
    {
        auto uri = QString::fromStdString(config->getValue<std::string>("hostUri"));
        this->selectThisUri(uri);
    }
    if (config->has("processName"))
    {
        auto name = QString::fromStdString(config->getValue<std::string>("processName"));
        _processNameEdit->setText(name);
    }
    if (config->has("numThreads"))
    {
        _numThreadsSpin->setValue(config->getValue<int>("numThreads"));
    }
    if (config->has("priority"))
    {
        _prioritySpin->setValue(int(config->getValue<double>("priority")*100));
    }
    if (config->has("affinityMode") and config->has("affinityMask"))
    {
        auto mode = config->getValue<std::string>("affinityMode");
        auto mask = config->getArray("affinityMask");
        std::vector<size_t> selection;
        for (size_t i = 0; i < mask->size(); i++) selection.push_back(mask->getElement<int>(i));
        _cpuSelection->setup(mode, selection);
    }
    if (config->has("yieldMode"))
    {
        auto mode = QString::fromStdString(config->getValue<std::string>("yieldMode"));
        for (int i = 0; i < _yieldModeBox->count(); i++)
        {
            if (_yieldModeBox->itemData(i).toString() == mode) _yieldModeBox->setCurrentIndex(i);
        }
    }
}
コード例 #5
0
void AuthorityServiceController::inquire()
{
	Poco::JSON::Object::Ptr pcfParameters;

	if ( data().has("filter") && data().isObject("filter") )
	{
		pcfParameters = data().getObject("filter");
		// There is a bug in MQCMD_INQUIRE_AUTH_SERVICE, AuthServiceAttrs is required!
		if ( !pcfParameters->has("AuthServiceAttrs") )
		{
			Poco::JSON::Array::Ptr attrs = new Poco::JSON::Array();
			attrs->add("All");
			pcfParameters->set("AuthServiceAttrs", attrs);
		}
	}
	else
	{
		pcfParameters = new Poco::JSON::Object();
		set("filter", pcfParameters);

		Poco::JSON::Array::Ptr attrs = new Poco::JSON::Array();
		formElementToJSONArray("AuthServiceAttrs", attrs);
		if ( attrs->size() == 0 ) // Nothing found for AuthServiceAttrs, try Attrs
		{
			formElementToJSONArray("Attrs", attrs);
		}
		if ( attrs->size() == 0 ) // Default must be specified for this command!
		{
			attrs->add("All");
		}
		pcfParameters->set("AuthServiceAttrs", attrs);

		if ( form().has("ServiceComponent") )
		{
			pcfParameters->set("ServiceComponent", form().get("ServiceComponent"));
		}

		handleFilterForm(pcfParameters);
	}

	AuthorityServiceMapper mapper(*commandServer(), pcfParameters);
	set("authservices", mapper.inquire());
}
コード例 #6
0
bool CSystemManager::getDevVersion(Poco::JSON::Object::Ptr& param, std::string& detail)
{
	CConfigManager* config = CConfigManager::instance();
	JSON::Object::Ptr pUpdate;
	config->getConfig("Update", pUpdate);
	if(pUpdate.isNull() || !pUpdate->has("infoPath"))
	{
		detail = "901";
		return false;
	}
	std::string infoPath = pUpdate->getValue<std::string>("infoPath");
	File file(infoPath);
	if(!file.exists())
	{
		detail = "465";
		return false;
	}
	Util::JSONConfiguration info;
	std::string version;
	std::string buildtime;
	try
	{
		info.load(infoPath);
		version = info.getString(UPDATE_VERSION_STR);
		buildtime = info.getString(UPDATE_BUILDTIME_STR);
	}
	catch(Exception& e)
	{
		detail = "465";
		warnf("%s, %d: Load device info file failed, %s", __FILE__, __LINE__, e.message().c_str());
		return false;
	}
	if(param->has(REG_TOKEN_STR))
	{
		param->remove(REG_TOKEN_STR);
	}
	param->set(SYSTEM_VERSION_STR, version);
	param->set(SYSTEM_BUILDTIME_STR, buildtime);
	return true;
}
コード例 #7
0
std::string Pothos::Topology::dumpJSON(const std::string &request)
{
    //extract input request
    Poco::JSON::Parser p; p.parse(request.empty()?"{}":request);
    auto configObj = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>();
    assert(configObj);
    const auto modeConfig = configObj->optValue<std::string>("mode", "flat");

    //parse request into traversal arguments
    const bool flatten = (modeConfig == "flat");
    const bool traverse = (modeConfig != "rendered");
    const auto &flows = (modeConfig == "rendered")?_impl->activeFlatFlows:_impl->flows;

    //replace rendered names with names from flattened hierarchy
    Poco::JSON::Object::Ptr flatBlocks;
    if (modeConfig == "rendered")
    {
        Poco::JSON::Parser pFlat; pFlat.parse(this->dumpJSON("{\"mode\":\"flat\"}"));
        auto flatObj = pFlat.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>();
        assert(flatObj);
        flatBlocks = flatObj->getObject("blocks");
        assert(flatBlocks);
    }

    //output object
    Poco::JSON::Object::Ptr topObj(new Poco::JSON::Object());

    //create blocks map
    Poco::JSON::Object::Ptr blocksObj(new Poco::JSON::Object());
    topObj->set("blocks", blocksObj);
    for (const auto &block : getObjSetFromFlowList(flows))
    {
        //gather block info
        Poco::JSON::Object::Ptr blockObj(new Poco::JSON::Object());
        const auto blockId = block.call<std::string>("uid");
        blocksObj->set(blockId, blockObj);

        //replace rendered names with names from flattened hierarchy
        blockObj->set("name", block.call<std::string>("getName"));
        if (flatBlocks and flatBlocks->has(blockId))
        {
            blockObj->set("name", flatBlocks->getObject(blockId)->getValue<std::string>("name"));
        }

        //input port info
        Poco::JSON::Array::Ptr inputsArray(new Poco::JSON::Array());
        for (const auto &portInfo : block.call<std::vector<PortInfo>>("inputPortInfo"))
        {
            inputsArray->add(portInfoToObj(portInfo));
        }
        if (inputsArray->size() > 0) blockObj->set("inputs", inputsArray);

        //output port info
        Poco::JSON::Array::Ptr outputsArray(new Poco::JSON::Array());
        for (const auto &portInfo : block.call<std::vector<PortInfo>>("outputPortInfo"))
        {
            outputsArray->add(portInfoToObj(portInfo));
        }
        if (outputsArray->size() > 0) blockObj->set("outputs", outputsArray);

        //sub-topology info
        if (traverse and this->uid() != blockId) try
        {
            auto subDump = block.call<std::string>("dumpJSON", "{\"mode\":\"top\"}");
            Poco::JSON::Parser psub; psub.parse(subDump);
            auto subObj = psub.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>();
            assert(subObj);
            std::vector<std::string> names; subObj->getNames(names);
            for (const auto &name : names) blockObj->set(name, subObj->get(name));
        }
        catch (const Pothos::Exception &){}
    }

    //create connections list
    Poco::JSON::Array::Ptr connsArray(new Poco::JSON::Array());
    topObj->set("connections", connsArray);
    for (const auto &flow : flows)
    {
        Poco::JSON::Object::Ptr connObj(new Poco::JSON::Object());
        connsArray->add(connObj);
        connObj->set("srcId", flow.src.uid);
        connObj->set("srcName", flow.src.name);
        connObj->set("dstId", flow.dst.uid);
        connObj->set("dstName", flow.dst.name);
    }

    //recursive flatten when instructed
    while (flatten and flattenDump(topObj));

    //return the string-formatted result
    std::stringstream ss; topObj->stringify(ss, 4);
    return ss.str();
}
コード例 #8
0
static bool blockIsHier(const Poco::JSON::Object::Ptr &blockObj)
{
    assert(blockObj);
    return blockObj->has("connections");
}
コード例 #9
0
/***********************************************************************
 * Parse a single documentation block for markup
 **********************************************************************/
static Poco::JSON::Object::Ptr parseCommentBlockForMarkup(const CodeBlock &commentBlock)
{
    Poco::JSON::Object::Ptr topObj(new Poco::JSON::Object());
    Poco::JSON::Array calls;
    Poco::JSON::Array keywords;
    Poco::JSON::Array::Ptr aliases(new Poco::JSON::Array());
    Poco::JSON::Array categories;
    Poco::JSON::Array params;
    Poco::JSON::Array::Ptr topDocs(new Poco::JSON::Array());
    Poco::JSON::Object::Ptr currentParam;

    std::string state;
    std::string indent;

    std::string instruction;
    std::string payload;

    //search for the markup begin tag and record the indent
    for (const auto &codeLine : commentBlock)
    {
        std::string line = codeLine.text;
        Poco::RegularExpression::MatchVec matches;

        if (not state.empty())
        {
            if (line.size() >= indent.size() and line.substr(0, indent.size()) != indent)
            {
                if (codeLine.lineNo == commentBlock.back().lineNo) line = "";
                else throw Pothos::SyntaxException("Inconsistent indentation", codeLine.toString());
            }

            if (line.size() >= indent.size()) line = line.substr(indent.size());
            else line = "";

            Poco::RegularExpression("^\\|(\\w+)\\s+(.*)$").match(line, 0, matches);
            if (not matches.empty())
            {
                assert(matches.size() == 3);
                instruction = line.substr(matches[1].offset, matches[1].length);
                payload = line.substr(matches[2].offset, matches[2].length);
            }
        }

        if (state.empty())
        {
            Poco::RegularExpression("^(.*)\\|PothosDoc\\s+(.*)$").match(line, 0, matches);
            if (matches.empty()) continue;
            assert(matches.size() == 3);
            indent = line.substr(matches[1].offset, matches[1].length);
            topObj->set("name", Poco::trim(line.substr(matches[2].offset, matches[2].length)));
            state = "DOC";
        }
        else if (matches.empty() and state == "DOC")
        {
            topDocs->add(line);
        }
        else if (matches.empty() and state == "PARAM")
        {
            auto array = currentParam->getArray("desc");
            array->add(line);
            currentParam->set("desc", stripDocArray(array));
        }
        else if (instruction == "category" and state == "DOC")
        {
            categories.add(Poco::trim(payload));
        }
        else if (instruction == "keywords" and state == "DOC")
        {
            for (const auto &keyword : Poco::StringTokenizer(
                payload, " \t", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY))
            {
                keywords.add(Poco::trim(keyword));
            }
        }
        else if (instruction == "alias" and state == "DOC")
        {
            const std::string alias(Poco::trim(payload));
            try {Pothos::PluginPath(alias);}
            catch (const Pothos::PluginPathError &)
            {
                throw Pothos::SyntaxException("Invalid alias path", codeLine.toString());
            }
            aliases->add(alias);
        }
        else if (instruction == "param" and (state == "DOC" or state == "PARAM"))
        {
            payload = bracketEscapeEncode(payload);
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)(\\s*\\[(.*)\\]\\s*)?(.*)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |param key[name] description",
                codeLine.toString());

            assert(fields.size() == 5);
            const std::string key = bracketEscapeDecode(Poco::trim(payload.substr(fields[1].offset, fields[1].length)));
            std::string name = titleCase(key);
            if (fields[3].length != 0) name = bracketEscapeDecode(Poco::trim(payload.substr(fields[3].offset, fields[3].length)));
            const std::string desc = bracketEscapeDecode(Poco::trim(payload.substr(fields[4].offset, fields[4].length)));

            currentParam = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
            params.add(currentParam);
            currentParam->set("key", key);
            currentParam->set("name", name);
            Poco::JSON::Array::Ptr descArr(new Poco::JSON::Array());
            descArr->add(desc);
            currentParam->set("desc", descArr);
            state = "PARAM";
        }
        else if (instruction == "default" and state == "PARAM")
        {
            if (currentParam->has("default")) throw Pothos::SyntaxException(
                "Multiple occurrence of |default for param",
                codeLine.toString());
            currentParam->set("default", payload);
        }
        else if (instruction == "units" and state == "PARAM")
        {
            if (currentParam->has("units")) throw Pothos::SyntaxException(
                "Multiple occurrence of |units for param",
                codeLine.toString());
            currentParam->set("units", payload);
        }
        else if (instruction == "widget" and state == "PARAM")
        {
            if (currentParam->has("widgetType")) throw Pothos::SyntaxException(
                "Multiple occurrence of |widget for param",
                codeLine.toString());
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |widget SpinBox(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string widgetType = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            currentParam->set("widgetType", widgetType);
            loadArgs(codeLine, *currentParam, argsStr, "widgetArgs", "widgetKwargs");
        }
        else if (instruction == "tab" and state == "PARAM")
        {
            if (currentParam->has("tab")) throw Pothos::SyntaxException(
                "Multiple occurrence of |tab for param",
                codeLine.toString());
            currentParam->set("tab", payload);
        }
        else if (instruction == "preview" and state == "PARAM")
        {
            if (currentParam->has("preview")) throw Pothos::SyntaxException(
                "Multiple occurrence of preview for param",
                codeLine.toString());
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)(\\s*\\((.*)\\))?$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |preview previewType(args...)",
                codeLine.toString());

            assert(fields.size() == 2 or fields.size() == 4);
            const std::string previewType = Poco::trim(payload.substr(fields[1].offset, fields[1].length));

            if (previewType != "disable" and
                previewType != "enable" and
                previewType != "valid" and
                previewType != "invalid" and
                previewType != "when"
            ) throw Pothos::SyntaxException(
                "Only supports enable/disable/valid/invalid/when as value for preview option of param",
                codeLine.toString());

            currentParam->set("preview", previewType);
            if (fields.size() == 4)
            {
                const std::string argsStr = Poco::trim(payload.substr(fields[3].offset, fields[3].length));
                loadArgs(codeLine, *currentParam, argsStr, "previewArgs", "previewKwargs");
            }
        }
        else if (instruction == "option" and state == "PARAM")
        {
            payload = bracketEscapeEncode(payload);
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^(\\s*\\[(.*)\\]\\s*)?(.*)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |option [name] value",
                codeLine.toString());

            assert(fields.size() == 4);
            const std::string value = bracketEscapeDecode(Poco::trim(payload.substr(fields[3].offset, fields[3].length)));
            std::string name = titleCase(value);
            if (fields[2].length != 0) name = bracketEscapeDecode(Poco::trim(payload.substr(fields[2].offset, fields[2].length)));

            Poco::JSON::Object option;
            option.set("value", value);
            option.set("name", name);
            if (not currentParam->has("options")) currentParam->set(
                "options", Poco::JSON::Array::Ptr(new Poco::JSON::Array()));
            currentParam->getArray("options")->add(option);
        }
        else if (instruction == "factory" and (state == "DOC" or state == "PARAM"))
        {
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(/.*)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |factory /registry/path(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string path = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            //add the path
            try {Pothos::PluginPath(path);}
            catch (const Pothos::PluginPathError &)
            {
                throw Pothos::SyntaxException("Invalid factory path", codeLine.toString());
            }
            if (topObj->has("path")) throw Pothos::SyntaxException(
                "Multiple occurrence of |factory", codeLine.toString());
            topObj->set("path", path);

            //split and extract args
            loadArgs(codeLine, *topObj, argsStr);

            state = "DOC";
        }
        else if ((instruction == "setter" or instruction == "initializer") and (state == "DOC" or state == "PARAM"))
        {
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |"+instruction+" setFooBar(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string callName = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            //add to calls
            Poco::JSON::Object call;
            call.set("type", instruction);
            call.set("name", callName);
            loadArgs(codeLine, call, argsStr);
            calls.add(call);

            state = "DOC";
        }
        else if (instruction == "mode" and (state == "DOC" or state == "PARAM"))
        {
            if (topObj->has("mode")) throw Pothos::SyntaxException(
                "Multiple occurrence of |mode",
                codeLine.toString());
            topObj->set("mode", payload);
        }
    }

    //empty state means this was a regular comment block, return null
    if (state.empty()) return Poco::JSON::Object::Ptr();

    topDocs = stripDocArray(topDocs);
    if (topDocs->size() > 0) topObj->set("docs", topDocs);
    if (categories.size() > 0) topObj->set("categories", categories);
    if (keywords.size() > 0) topObj->set("keywords", keywords);
    if (aliases->size() > 0) topObj->set("aliases", aliases);
    if (params.size() > 0) topObj->set("params", params);
    if (calls.size() > 0) topObj->set("calls", calls);

    //sanity check for required stuff
    if (not topObj->has("path"))
    {
        throw Pothos::SyntaxException("missing |factory declaration");
    }

    return topObj;
}
コード例 #10
0
void Dictionary::mapToJSON(const PCF& pcf, Poco::JSON::Object::Ptr& json, bool alwaysCreate) const
{
	std::vector<MQLONG> parameters = pcf.getParameters();
	for(std::vector<MQLONG>::iterator it = parameters.begin(); it != parameters.end(); ++it)
	{
		std::string name = getName(*it);
		if ( name.empty() )
		{
			if ( alwaysCreate )
			{
				name = "id_" + Poco::NumberFormatter::format(*it);
			}
			else
			{
				continue;
			}
		}

		if ( json->has(name) ) continue; // Don't overwrite already added properties

		Poco::JSON::Object::Ptr field = new Poco::JSON::Object();
		json->set(name, field);

		field->set("id", *it);

		if ( pcf.isNumber(*it) )
		{
			MQLONG value = pcf.getParameterNum(*it);
			field->set("value", value);

			if ( hasDisplayMap(*it) )
			{
				std::string displayValue = getDisplayValue(*it, value);
				if ( displayValue.empty() )
				{
					displayValue = "Unknown value " + Poco::NumberFormatter::format(value) + " for " + Poco::NumberFormatter::format(*it);
				}
				field->set("display", displayValue);
			}
		}
		else if ( pcf.isString(*it) )
		{
			field->set("value", pcf.getParameterString(*it));
		}
		else if ( pcf.isNumberList(*it) )
		{
			std::vector<MQLONG> values = pcf.getParameterNumList(*it);
			Poco::JSON::Array::Ptr jsonValues = new Poco::JSON::Array();
			field->set("value", jsonValues);

			if ( hasDisplayMap(*it) )
			{
				for(std::vector<MQLONG>::iterator vit = values.begin(); vit != values.end(); ++vit)
				{
					Poco::JSON::Object::Ptr jsonValueObject = new Poco::JSON::Object();

					std::string displayValue = getDisplayValue(*it, *vit);
					if ( displayValue.empty() )
					{
						displayValue = "Unknown value " + Poco::NumberFormatter::format(*vit) + " for " + Poco::NumberFormatter::format(*it);
					}
					jsonValueObject->set("value", *vit);
					jsonValueObject->set("display", displayValue);
					jsonValues->add(jsonValueObject);
				}
			}
			else
			{
				for(std::vector<MQLONG>::iterator vit = values.begin(); vit != values.end(); ++vit)
				{
					jsonValues->add(*vit);
				}
			}
		}
		else if ( pcf.isStringList(*it) )
		{
			Poco::JSON::Array::Ptr jsonValues = new Poco::JSON::Array();
			field->set("value", jsonValues);

			std::vector<std::string> strings = pcf.getParameterStringList(*it);
			for(std::vector<std::string>::iterator vit = strings.begin(); vit != strings.end(); ++vit)
			{
				jsonValues->add(*vit);
			}
		}
		else
		{
			poco_assert_dbg(false);
		}
	}
}
コード例 #11
0
void Controller::ingestRequest(const Poco::Dynamic::Var& request) {
    if (request.type() != typeid(Poco::JSON::Array::Ptr)) {
        throw RequestException("Invalid JSON format, root must be array.");
    }
    
    try {
        Poco::JSON::Array::Ptr jsonArray = request.extract<Poco::JSON::Array::Ptr>();
        
        for (Poco::JSON::Array::ConstIterator it = jsonArray->begin(); it != jsonArray->end(); it++) {
            Poco::JSON::Object::Ptr json = it->extract<Poco::JSON::Object::Ptr>();
            
            Record record;
            vector<uint8_t>* image_data = NULL;
            
            if (json->has("id")) {
                record.setId(json->getValue<string>("id"));
            }
            if (json->has("thumbnail")) {
                record.setThumbnail(json->getValue<string>("thumbnail"));
            }
            if (json->has("metadata")) {
                record.setMetadata(json->getValue<string>("metadata"));
            }
            if (json->has("blockHash")) {
                record.getHashes()[BlockHash] = str2bin(json->getValue<string>("blockHash"));
            }
            if (json->has("dHash")) {
                record.getHashes()[DHash] = str2bin(json->getValue<string>("dHash"));
            }
            if (json->has("gaussDHash")) {
                record.getHashes()[GaussDHash] = str2bin(json->getValue<string>("gaussDHash"));
            }
            if (json->has("gauss2DHash")) {
                record.getHashes()[Gauss2DHash] = str2bin(json->getValue<string>("gauss2DHash"));
            }
            if (json->has("gaussBlockHash")) {
                record.getHashes()[GaussBlockHash] = str2bin(json->getValue<string>("gaussBlockHash"));
            }
            if (json->has("image_base64")) {
                image_data = Image::fromBase64(json->getValue<string>("image_base64"));
            }
            if (!image_data && json->has("image_url")) {
                image_data = Image::fromUrl(json->getValue<string>("image_url"));
            }
            
            if (json->has("status")) {
                string status = json->getValue<string>("status");
                if (status == "deleted") {
                    deleteRequest(record);
                    continue;
                } else {
                    throw RequestException("Invalid status value.");
                }
            }

            if (image_data) {
                HashAlgorithmManager::getInstance().attachHashes(record, image_data);
                delete image_data;
            }
            putRequest(record);
        }
    } catch (Poco::JSON::JSONException& e) {
        throw RequestException("Invalid JSON format.");
    }
    appio::print_ok("Data was successfully changed.");
}