如何从 ModelNode 结果中获取特定对象

How to get specific object from ModelNode result

我使用 ModelControllerClient 来获取有关在 Wildfly 服务器 上使用的记录器的一些信息。 我想要一个所有记录器名称的列表。

这就是我获取有关记录器的所有信息的方式:

ModelNode op = new ModelNode();
op.get("operation").set("read-resource");

ModelNode address = op.get("address");
address.add("subsystem", "logging");
address.add("logger", "*");

ModelNode result = client.execute(op);

这是我得到的 ModelNode 结果的一个小例子。

{
        "address" => [
            ("subsystem" => "logging"),
            ("logger" => "jacorb")
        ],
        "outcome" => "success",
        "result" => {
            "category" => "jacorb",
            "filter" => undefined,
            "filter-spec" => undefined,
            "handlers" => undefined,
            "level" => "WARN",
            "use-parent-handlers" => true
        }
    },
    {
        "address" => [
            ("subsystem" => "logging"),
            ("logger" => "jacorb.config")
        ],
        "outcome" => "success",
        "result" => {
            "category" => "jacorb.config",
            "filter" => undefined,
            "filter-spec" => undefined,
            "handlers" => undefined,
            "level" => "ERROR",
            "use-parent-handlers" => true
        }
    },

我只想获取 "logger" / "category" 的值。

我试图通过以下方式获取记录器的名称:

result.get("logger");

但它返回 "undefined"。我想问题是我有不止一个对象 "logger"。当我用 "category" 尝试时,也会发生同样的情况。

您需要先阅读结果。在简单的情况下,它将是 result.get("result", "logger")。您还可以使用 Operations API 并执行类似 Operations.readResult(result).get("logger").

的操作

如果您只需要记录器名称,这里有一个示例:

try (ModelControllerClient client = ModelControllerClient.Factory.create("localhost", 9990)) {
    final ModelNode address = Operations.createAddress("subsystem", "logging");
    final ModelNode op = Operations.createOperation(ClientConstants.READ_CHILDREN_NAMES_OPERATION, address);
    op.get(ClientConstants.CHILD_TYPE).set("logger");
    final ModelNode result = client.execute(op);
    if (Operations.isSuccessfulOutcome(result)) {
        final List<ModelNode> loggerNames = Operations.readResult(result).asList();
        for (ModelNode loggerName : loggerNames) {
            System.out.printf("logger=%s%n", loggerName.asString());
        }
    } else {
        System.err.printf("Failed to get the logger names: %s%n", Operations.getFailureDescription(result).asString());
    }
}

如果您想要完整的描述,您可以使用 read-children-resource 操作。

此外,WildFly 文档中有一节是关于 using the ModelControllerClient and the ModelNode and ModelType API 的。