Java Code Examples for org.jboss.dmr.ModelNode#fromJSONString()

The following examples show how to use org.jboss.dmr.ModelNode#fromJSONString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParamVerify.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public static FormValidation doCheckJsonyaml(@QueryParameter String value)
        throws IOException, ServletException {
    if (value.length() == 0)
        return FormValidation.error("You must set a block of JSON or YAML");
    try {
        ModelNode.fromJSONString(value);
    } catch (Throwable t) {
        try {
            Yaml yaml = new Yaml(new SafeConstructor());
            Map<String, Object> map = (Map<String, Object>) yaml
                    .load(value);
            JSONObject jsonObj = JSONObject.fromObject(map);
            ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t2) {
            return FormValidation
                    .error("Valid JSON or YAML must be specified");
        }
    }
    return FormValidation.ok();
}
 
Example 2
Source File: IOpenShiftApiObjHandler.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
default ModelNode hydrateJsonYaml(String jsonyaml, TaskListener listener) {
    // construct json/yaml node
    ModelNode resources = null;
    try {
        resources = ModelNode.fromJSONString(jsonyaml);
    } catch (Exception e) {
        Yaml yaml = new Yaml(new SafeConstructor());
        Map<String, Object> map = (Map<String, Object>) yaml.load(jsonyaml);
        JSONObject jsonObj = JSONObject.fromObject(map);
        try {
            resources = ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t) {
            if (listener != null)
                t.printStackTrace(listener.getLogger());
        }
    }
    return resources;
}
 
Example 3
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Check if the server is in restart-required state, that means
 * management operation return "response-headers" : {"process-state" : "restart-required"}
 *
 * @return true if the server is in "restart-required" state
 * @throws Exception
 */
public static boolean doesServerRequireRestart() throws Exception {
    try (CLIWrapper cli = new CLIWrapper(true)) {
        cli.sendLine("patch info --json-output", true);
        String response = cli.readOutput();
        ModelNode responseNode = ModelNode.fromJSONString(response);
        ModelNode respHeaders = responseNode.get("response-headers");
        if (respHeaders != null && respHeaders.isDefined()) {
            ModelNode processState = respHeaders.get("process-state");
            return processState != null && processState.isDefined() && processState.asString()
                    .equals(ClientConstants.CONTROLLER_PROCESS_STATE_RESTART_REQUIRED);
        } else {
            return false;
        }
    }
}
 
Example 4
Source File: AnalysisContextTest.java    From revapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigurationHandling_mergeNewStyle_withIds() throws Exception {
    Dummy.schema = "{\"type\": \"object\", \"properties\": {\"a\": {\"type\": \"integer\"}," +
            " \"b\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}}}";
    Dummy.extensionId = "ext";
    ModelNode cfg1 = ModelNode.fromJSONString("[{\"extension\": \"ext\", \"id\": \"a\", \"configuration\": {\"a\": 1, \"b\": [\"x\"]}}]");
    ModelNode cfg2 = ModelNode.fromJSONString("[{\"extension\": \"ext\", \"id\": \"a\", \"configuration\": {\"b\": [\"y\"]}}," +
            "{\"extension\": \"ext\", \"id\": \"b\", \"configuration\": {\"b\": [\"y\"]}}]");
    ModelNode newCfg = ModelNode.fromJSONString(
            "[{\"extension\": \"ext\", \"id\": \"a\", \"configuration\": {\"a\": 1, \"b\": [\"x\", \"y\"]}}," +
                    "{\"extension\": \"ext\", \"id\": \"b\", \"configuration\": {\"b\": [\"y\"]}}]");

    Revapi revapi = Revapi.builder().withAnalyzers(Dummy.class).withReporters(TestReporter.class).build();

    AnalysisContext ctx = AnalysisContext.builder(revapi)
            .withConfiguration(cfg1)
            .mergeConfiguration(cfg2)
            .build();

    Assert.assertEquals(newCfg, ctx.getConfiguration());
}
 
Example 5
Source File: TypeConverters.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public ModelNode toModelNode(Object o) {
    if (o == null) {
        return new ModelNode();
    }
    if (o instanceof CompositeData) {
        final ModelNode node = new ModelNode();
        final CompositeData composite = (CompositeData)o;
        for (String key : composite.getCompositeType().keySet()) {
            if (!typeNode.hasDefined(key)){
                throw JmxLogger.ROOT_LOGGER.unknownValue(key);
            }
            TypeConverter converter = getConverter(typeNode.get(key, TYPE), typeNode.get(key, VALUE_TYPE));
            node.get(key).set(converter.toModelNode(composite.get(key)));
        }
        return node;
    } else {
        return ModelNode.fromJSONString((String)o);
    }
}
 
Example 6
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Rollback cumulative patch, online!!
 *
 * @param resetConfiguration
 * @return true if operation was successful or false if at least one rollback failed
 * @throws Exception
 */
public static boolean rollbackCumulativePatch(boolean resetConfiguration) throws Exception {
    final String infoCommand = "patch info --json-output";
    final String rollbackCommand = "patch rollback --patch-id=%s --reset-configuration=%s";
    try (CLIWrapper cli = new CLIWrapper(true)) {
        String command = infoCommand;
        logger.debug("----- sending command to CLI: " + command + " -----");
        cli.sendLine(command);
        String response = cli.readOutput();
        ModelNode responseNode = ModelNode.fromJSONString(response);
        String cumulativePatchId = responseNode.get("result").get("cumulative-patch-id").asString();
        command = String.format(rollbackCommand, cumulativePatchId, resetConfiguration);
        logger.debug("----- sending command to CLI: " + command + " -----");
        return cli.sendLine(command, true);
    }
}
 
Example 7
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Rollback cumulative patch and all picked up one-offs, offline
 *
 * @return true if operation was successful or false if at least one rollback failed
 * @throws Exception
 */
public static boolean rollbackAll() throws Exception {
    CLIWrapper cli = null;
    boolean success = true;
    try {
        cli = new CLIWrapper(false);
        cli.sendLine("patch info --streams --json-output");
        final ModelNode response = ModelNode.fromJSONString(cli.readOutput());
        for(ModelNode stream : response.get(ModelDescriptionConstants.RESULT).asList()) {
            success = success && rollbackAll(cli, stream.asString());
        }
        return success;
    } finally {
        if (cli != null) {
            cli.quit();
        }
    }
}
 
Example 8
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Rollback all installed oneoffs, offline!!
 *
 * @return true if operation was successful or false if at least one rollback failed
 * @throws Exception
 */
public static boolean rollbackAllOneOffs() throws Exception {
    boolean success = true;
    final String infoCommand = "patch info --distribution=%s --json-output";
    final String rollbackCommand = "patch rollback --patch-id=%s --distribution=%s --reset-configuration=true --override-all";
    try (CLIWrapper cli = new CLIWrapper(false)) {
        String command = String.format(infoCommand, PatchingTestUtil.AS_DISTRIBUTION);
        logger.debug("----- sending command to CLI: " + command + " -----");
        cli.sendLine(command);
        String response = cli.readOutput();
        ModelNode responseNode = ModelNode.fromJSONString(response);
        List<ModelNode> patchesList = responseNode.get("result").get("patches").asList();
        for (ModelNode n : patchesList) {
            command = String.format(rollbackCommand, n.asString(), PatchingTestUtil.AS_DISTRIBUTION);
            logger.debug("----- sending command to CLI: " + command + " -----");
            success = success && cli.sendLine(command, true);
        }
        return success;
    }
}
 
Example 9
Source File: ConvertToXmlConfigMojo.java    From revapi with Apache License 2.0 6 votes vote down vote up
private static Map<String, ModelNode> getKnownExtensionSchemas(AnalysisResult.Extensions extensions)
        throws IOException {
    List<Configurable> exts = extensions.stream().map(e -> (Configurable) e.getKey().getInstance())
            .collect(Collectors.toList());

    Map<String, ModelNode> extensionSchemas = new HashMap<>();
    for (Configurable ext : exts) {
        String extensionId = ext.getExtensionId();
        if (extensionId == null || extensionSchemas.containsKey(extensionId)) {
            continue;
        }

        try (Reader schemaRdr = ext.getJSONSchema()) {
            if (schemaRdr == null) {
                continue;
            }

            ModelNode schema = ModelNode.fromJSONString(readFull(schemaRdr));

            extensionSchemas.put(extensionId, schema);
        }
    }

    return extensionSchemas;
}
 
Example 10
Source File: AttachmentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void test1() throws CliInitializationException {
    // 10 files should be replaced by indexes.
    ModelNode description = ModelNode.fromJSONString(DESCRIPTION);
    ModelNode value = ModelNode.fromJSONString(VALUE);
    ModelNode expected = ModelNode.fromJSONString(RESULT);
    ModelNode req = description.get(Util.REQUEST_PROPERTIES).asObject();
    Attachments attachments = new Attachments();
    CommandContext ctx = CommandContextFactory.getInstance().newCommandContext();
    for (String k : value.keys()) {
        Util.applyReplacements(ctx, k, value.get(k), req.get(k), req.get(k).get(Util.TYPE).asType(), attachments);
    }
    Assert.assertEquals("Should be equal", expected, value);
    Assert.assertEquals(11, attachments.getAttachedFiles().size());
    for (int i = 0; i < attachments.getAttachedFiles().size(); i++) {
        String p = attachments.getAttachedFiles().get(i);
        Assert.assertEquals(p, EXPECTED_PATH + i);
    }
}
 
Example 11
Source File: ConfigurationValidatorTest.java    From revapi with Apache License 2.0 6 votes vote down vote up
private ValidationResult test(String object, final String extensionId, final String schema) {
    ConfigurationValidator validator = new ConfigurationValidator();

    ModelNode fullConfig = ModelNode.fromJSONString(object);

    Configurable fakeConfigurable = new Configurable() {
        @Nullable
        @Override
        public String getExtensionId() {
            return extensionId;
        }

        @Nullable
        @Override
        public Reader getJSONSchema() {
            return new StringReader(schema);
        }

        @Override
        public void initialize(@Nonnull AnalysisContext analysisContext) {
        }
    };

    return validator.validate(fullConfig, fakeConfigurable);
}
 
Example 12
Source File: AttachmentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testInvalidValueType() throws CliInitializationException {
    // 10 files should be replaced by indexes.
    ModelNode description = ModelNode.fromJSONString(VAULT_ADD_DESCRIPTION);
    ModelNode value = ModelNode.fromJSONString(VAULT_ADD_VALUE);
    ModelNode req = description.get(Util.REQUEST_PROPERTIES).asObject();
    Attachments attachments = new Attachments();
    CommandContext ctx = CommandContextFactory.getInstance().newCommandContext();
    for (String k : value.keys()) {
        Util.applyReplacements(ctx, k, value.get(k), req.get(k), req.get(k).get(Util.TYPE).asType(), attachments);
    }
}
 
Example 13
Source File: HttpMgmtProxy.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ModelNode sendPostCommand(ModelNode cmd, boolean ignoreFailure) throws Exception {
    String cmdStr = cmd.toJSONString(true);
    HttpPost post = new HttpPost(url.toURI());
    StringEntity entity = new StringEntity(cmdStr);
    entity.setContentType(APPLICATION_JSON);
    post.setEntity(entity);

    HttpResponse response = httpClient.execute(post, httpContext);
    String str = EntityUtils.toString(response.getEntity());
    if (response.getStatusLine().getStatusCode() == StatusCodes.OK || ignoreFailure) {
        return ModelNode.fromJSONString(str);
    }
    throw new Exception("Could not execute command: " + str);
}
 
Example 14
Source File: ConvertToXmlConfigMojo.java    From revapi with Apache License 2.0 5 votes vote down vote up
private static PlexusConfiguration convertToXml(Map<String, ModelNode> extensionSchemas, String xmlOrJson)
        throws IOException, XmlPullParserException {
    ModelNode jsonConfig;
    try {
        jsonConfig = ModelNode.fromJSONString(JSONUtil.stripComments(xmlOrJson));
    } catch (IllegalArgumentException e) {
        //ok, this already is XML
        return null;
    }
    return SchemaDrivenJSONToXmlConverter.convertToXml(extensionSchemas, jsonConfig);
}
 
Example 15
Source File: CheckSpecificConfigurationTest.java    From revapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckConfigurationInSchema() throws Exception {
    class FakeCheck extends CheckBase {
        @Override
        public EnumSet<Type> getInterest() {
            return null;
        }

        @Nullable
        @Override
        public String getExtensionId() {
            return "testCheck";
        }

        @Nullable
        @Override
        public Reader getJSONSchema() {
            return new StringReader("{\"type\": \"boolean\"}");
        }
    }

    JavaApiAnalyzer analyzer = new JavaApiAnalyzer(Collections.singleton(new FakeCheck()), Collections.emptyList());

    try (Reader rdr = analyzer.getJSONSchema()) {
        ModelNode schema = ModelNode.fromJSONString(slurp(rdr));
        Assert.assertTrue("boolean".equals(schema.get("properties", "checks", "properties", "testCheck", "type").asString()));
    }
}
 
Example 16
Source File: OpenshiftStartedEnvironment.java    From pnc with Apache License 2.0 5 votes vote down vote up
private ModelNode createModelNode(String resourceDefinition, Map<String, String> runtimeProperties) {
    Properties properties = new Properties();
    properties.putAll(runtimeProperties);
    String definition = StringPropertyReplacer.replaceProperties(resourceDefinition, properties);
    if (logger.isTraceEnabled()) {
        logger.trace("Node definition: " + secureLog(definition));
    }

    return ModelNode.fromJSONString(definition);
}
 
Example 17
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Use CLI to get the cumulative patch id
 *
 * @return the current cumulative patch id (string)
 * @throws Exception
 */
public static String getCumulativePatchId() throws Exception {
    try (CLIWrapper cli = new CLIWrapper(true)) {
        cli.sendLine("patch info --json-output");
        String response = cli.readOutput();
        ModelNode responseNode = ModelNode.fromJSONString(response);
        return responseNode.get("result").get("cumulative-patch-id").asString();
    }
}
 
Example 18
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default boolean didImageChangeFromPreviousVersion(IClient client,
        int latestVersion, boolean chatty, TaskListener listener,
        String depCfg, String namespace, String latestImageHexID,
        String imageTag) {
    // now get previous RC, fetch image Hex ID, and compare
    int previousVersion = latestVersion - 1;
    if (previousVersion < 1) {
        if (chatty)
            listener.getLogger().println(
                    "\n first version skip image compare");
        return true;
    }
    IReplicationController prevRC = null;
    try {
        prevRC = client.get(ResourceKind.REPLICATION_CONTROLLER, depCfg
                + "-" + previousVersion, namespace);
    } catch (Throwable t) {
        if (chatty)
            t.printStackTrace(listener.getLogger());
    }

    if (prevRC == null) {
        listener.getLogger().println(
                "\n\n could not obtain previous replication controller");
        return false;
    }

    // get the dc again from the rc vs. passing the dc in aIClient client,
    // IDeploymentConfig dc, String imageTag, boolean chatty, TaskListener
    // listener, long wait)s a form of cross reference verification
    String dcJson = prevRC
            .getAnnotation("openshift.io/encoded-deployment-config");
    if (dcJson == null || dcJson.length() == 0) {
        listener.getLogger()
                .println(
                        "\n\n associated DeploymentConfig for previous ReplicationController missing");
        return false;
    }
    ModelNode dcNode = ModelNode.fromJSONString(dcJson);
    IDeploymentConfig dc = new DeploymentConfig(dcNode, client, null);
    String previousImageHexID = dc
            .getImageHexIDForImageNameAndTag(imageTag);

    if (previousImageHexID == null || previousImageHexID.length() == 0) {
        // don't count ill obtained prev image id as successful image id
        // change
        listener.getLogger()
                .println(
                        "\n\n could not obtain hex image ID for previous deployment");
        return false;
    }

    if (latestImageHexID.equals(previousImageHexID)) {
        if (chatty)
            listener.getLogger().println(
                    "\n images still the same " + latestImageHexID);
        return false;
    } else {
        if (chatty)
            listener.getLogger().println(
                    "\n image did change, new image " + latestImageHexID
                            + " old image " + previousImageHexID);
        return true;
    }
}
 
Example 19
Source File: HttpMgmtProxy.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ModelNode sendGetCommand(String cmd) throws Exception {
    return ModelNode.fromJSONString(sendGetCommandJson(cmd));
}
 
Example 20
Source File: AbstractAuditLogHandlerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void checkOpsEqual(ModelNode rawDmr, ModelNode fromLog) {
    ModelNode expected = ModelNode.fromJSONString(rawDmr.toJSONString(true));
    Assert.assertEquals(expected, fromLog);

}