Java Code Examples for org.jboss.dmr.ModelNode

The following are top voted examples for showing how to use org.jboss.dmr.ModelNode. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xtf   File: KubernetesVersion.java   View source code 6 votes vote down vote up
public static synchronized KubernetesVersion get() {
	if (INSTANCE != null) {
		return INSTANCE;
	}

	try {
		String versionJson = HttpClient.get(TestConfiguration.masterUrl() + "/version").response();
		ModelNode version = ModelNode.fromJSONString(versionJson);
		int major = Integer.parseInt(version.get("major").asString());
		int minor = Integer.parseInt(version.get("minor").asString());
		INSTANCE = new KubernetesVersion(major, minor);
	} catch (Exception e) {
		LOGGER.error("Error getting Kubernetes version from master", e);
		INSTANCE = new KubernetesVersion(0, 0);
	}

	return INSTANCE;
}
 
Example 2
Project: xtf   File: SsoTokenRequestor.java   View source code 6 votes vote down vote up
/**
 * Request new token from sso instance
 *
 * @return this instance
 * @throws IOException in case of request failure
 */
public TokenHolder requestNewToken() throws IOException {
	final String params = buildParams();
	final String url = ssoAuthUrl + "/realms/" + realm + "/protocol/openid-connect/token";

	log.info("Token request: {}", url);
	log.info("Request params: {} ", params);
	final String response = HttpClient.post(url)
		.data(params, ContentType.APPLICATION_FORM_URLENCODED)
		.response();

	ModelNode tokenResponse = ModelNode.fromJSONString(response);
	log.debug("Token response: {}", tokenResponse);

	return new TokenHolder(tokenResponse);
}
 
Example 3
Project: wildfly-microprofile-config   File: SubsystemAdd.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {

    MicroProfileConfigLogger.ROOT_LOGGER.activatingSubsystem();

    ConfigProviderService.install(context);

    //Add deployment processors here
    //Remove this if you don't need to hook into the deployers, or you can add as many as you like
    //see SubDeploymentProcessor for explanation of the phases
    context.addStep(new AbstractDeploymentChainStep() {
        public void execute(DeploymentProcessorTarget processorTarget) {
            processorTarget.addDeploymentProcessor(SubsystemExtension.SUBSYSTEM_NAME, DependencyProcessor.PHASE, DependencyProcessor.PRIORITY, new DependencyProcessor());
            processorTarget.addDeploymentProcessor(SubsystemExtension.SUBSYSTEM_NAME, SubsystemDeploymentProcessor.PHASE, SubsystemDeploymentProcessor.PRIORITY, new SubsystemDeploymentProcessor());

        }
    }, OperationContext.Stage.RUNTIME);

}
 
Example 4
Project: wildfly-microprofile-health   File: WildFlyResponseFactory.java   View source code 6 votes vote down vote up
private Map<String,Object> setData(ModelNode model) {
    if (!model.isDefined()) {
        return null;
    }
    Map<String, Object> data = new HashMap<>();
    for (String key : model.keys()) {
        final ModelNode modelValue = model.get(key);
        final Object value;
        switch (modelValue.getType()) {
            case LONG:
                value = modelValue.asLong();
                break;
            case BOOLEAN:
                value = modelValue.asBoolean();
                break;
            default:
                value = modelValue.asString();
        }
        data.put(key, value);
    }
    return data;
}
 
Example 5
Project: wildfly-microprofile-health   File: CheckOperation.java   View source code 6 votes vote down vote up
public static ModelNode computeResult(Collection<HealthCheckResponse> statuses) {
   ModelNode result = new ModelNode();
   boolean globalOutcome = true;
   result.get("checks").setEmptyList();
   for (HealthCheckResponse status : statuses) {
      ModelNode responseNode = new ModelNode();
      responseNode.get("name").set(status.getName());
      HealthCheckResponse.State state = status.getState();
      globalOutcome = globalOutcome & state == UP;
      responseNode.get("state").set(state.toString());
      if (status.getData().isPresent()) {
         responseNode.get("data").setEmptyObject();
         Map<String, Object> attributes = status.getData().get();
         for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            responseNode.get("data").get(entry.getKey()).set(entry.getValue().toString());
         }
      }
      result.get("checks").add(responseNode);
   }
   result.get("outcome").set(globalOutcome ? "UP" : "DOWN");
   return result;
}
 
Example 6
Project: wildfly-nosql   File: Neo4jDriverSubsystemAdd.java   View source code 6 votes vote down vote up
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws
        OperationFailedException {

    runtimeValidator.validate(operation.resolve());
    context.addStep(new AbstractDeploymentChainStep() {
        protected void execute(DeploymentProcessorTarget processorTarget) {
            final int PARSE_NEO4J_DRIVER                          = 0x4C00;
            final int DEPENDENCIES_NEO4J_DRIVER                   = 0x1F10;
            // TODO: use Phase.PARSE_NEO4J_DRIVER
            processorTarget.addDeploymentProcessor(Neo4jDriverExtension.SUBSYSTEM_NAME, Phase.PARSE, PARSE_NEO4J_DRIVER, new DriverScanDependencyProcessor("neo4jsubsystem"));
            // TODO: use Phase.DEPENDENCIES_NEO4J_DRIVER
            processorTarget.addDeploymentProcessor(Neo4jDriverExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_NEO4J_DRIVER, DriverDependencyProcessor.getInstance());
        }
    }, OperationContext.Stage.RUNTIME);

    startNeo4jDriverSubsysteService(context);

}
 
Example 7
Project: wildfly-nosql   File: OrientDriverSubsystemAdd.java   View source code 6 votes vote down vote up
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model)
        throws OperationFailedException {
    runtimeValidator.validate(operation.resolve());
    context.addStep(new AbstractDeploymentChainStep() {
        protected void execute(DeploymentProcessorTarget processorTarget) {
            final int PARSE_ORIENT_DRIVER                         = 0x4C01;
            final int DEPENDENCIES_ORIENT_DRIVER                  = 0x1F11;
            // TODO: use Phase.PARSE_ORIENT_DRIVER
            processorTarget.addDeploymentProcessor(OrientDriverExtension.SUBSYSTEM_NAME, Phase.PARSE,
                    PARSE_ORIENT_DRIVER, new DriverScanDependencyProcessor("orientdbsubsystem"));
            // TODO: use Phase.DEPENDENCIES_ORIENT_DRIVER
            processorTarget.addDeploymentProcessor(OrientDriverExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES,
                    DEPENDENCIES_ORIENT_DRIVER, DriverDependencyProcessor.getInstance());
        }
    }, OperationContext.Stage.RUNTIME);

    startOrientSubsystemService(context);
}
 
Example 8
Project: wildfly-nosql   File: CassandraDriverSubsystemAdd.java   View source code 6 votes vote down vote up
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws
        OperationFailedException {

    runtimeValidator.validate(operation.resolve());
    context.addStep(new AbstractDeploymentChainStep() {
        protected void execute(DeploymentProcessorTarget processorTarget) {
            final int PARSE_CASSANDRA_DRIVER                      = 0x4C02;
            final int DEPENDENCIES_CASSANDRA_DRIVER               = 0x1F12;
            // TODO: use Phase.PARSE_CASSANDRA_DRIVER
            processorTarget.addDeploymentProcessor(CassandraDriverExtension.SUBSYSTEM_NAME, Phase.PARSE, PARSE_CASSANDRA_DRIVER, new DriverScanDependencyProcessor("cassandrasubsystem"));
            // TODO: use Phase.DEPENDENCIES_CASSANDRA_DRIVER
            processorTarget.addDeploymentProcessor(CassandraDriverExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_CASSANDRA_DRIVER, DriverDependencyProcessor.getInstance());
        }
    }, OperationContext.Stage.RUNTIME);

    startCassandraDriverSubsysteService(context);
}
 
Example 9
Project: wildfly-nosql   File: CustomModuleTestCase.java   View source code 6 votes vote down vote up
@Override
public final void setup(final ManagementClient managementClient, final String containerId) throws Exception {
    setManagementClient(managementClient);
    ModelNode address = new ModelNode();
    address.add("subsystem", "neo4j");
    address.add("neo4j", "default");
    address.protect();

    final ModelNode operation = new ModelNode();
    operation.get(OP_ADDR).set(address);
    operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
    operation.get(NAME).set("module");
    operation.get(VALUE).set("org.neo4j.driver:test");
    ModelNode result = executeOperation(operation);
    reload();
}
 
Example 10
Project: wildfly-nosql   File: CustomModuleTestCase.java   View source code 6 votes vote down vote up
@Override
public final void setup(final ManagementClient managementClient, final String containerId) throws Exception {
    setManagementClient(managementClient);
    ModelNode address = new ModelNode();
    address.add("subsystem", "orientdb");
    address.add("orient", "default");
    address.protect();

    final ModelNode operation = new ModelNode();
    operation.get(OP_ADDR).set(address);
    operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
    operation.get(NAME).set("module");
    operation.get(VALUE).set("com.orientechnologies:test");
    ModelNode result = executeOperation(operation);
    reload();
}
 
Example 11
Project: wildfly-nosql   File: CustomModuleTestCase.java   View source code 6 votes vote down vote up
@Override
public final void setup(final ManagementClient managementClient, final String containerId) throws Exception {
    setManagementClient(managementClient);
    ModelNode address = new ModelNode();
    address.add("subsystem", "cassandra");
    address.add("cassandra", "default");
    address.protect();

    final ModelNode operation = new ModelNode();
    operation.get(OP_ADDR).set(address);
    operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
    operation.get(NAME).set("module");
    operation.get(VALUE).set("com.datastax.cassandra.driver-core:test");
    ModelNode result = executeOperation(operation);
    reload();
}
 
Example 12
Project: wildfly-nosql   File: CustomModuleTestCase.java   View source code 6 votes vote down vote up
@Override
public final void setup(final ManagementClient managementClient, final String containerId) throws Exception {
    setManagementClient(managementClient);
    ModelNode address = new ModelNode();
    address.add("subsystem", "mongodb");
    address.add("mongo", "default");
    address.protect();

    final ModelNode operation = new ModelNode();
    operation.get(OP_ADDR).set(address);
    operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
    operation.get(NAME).set("module");
    operation.get(VALUE).set("org.mongodb.driver:test");
    ModelNode result = executeOperation(operation);
    reload();
}
 
Example 13
Project: wildfly-nosql   File: MongoDriverSubsystemAdd.java   View source code 6 votes vote down vote up
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws
        OperationFailedException {

    runtimeValidator.validate(operation.resolve());
    context.addStep(new AbstractDeploymentChainStep() {
        protected void execute(DeploymentProcessorTarget processorTarget) {
            final int PARSE_MONGO_DRIVER                          = 0x4C03;
            final int DEPENDENCIES_MONGO_DRIVER                   = 0x1F13;
            // TODO: use Phase.PARSE_MONGO_DRIVER
            processorTarget.addDeploymentProcessor(MongoDriverExtension.SUBSYSTEM_NAME, Phase.PARSE, PARSE_MONGO_DRIVER, new DriverScanDependencyProcessor("mongodbsubsystem"));
            // TODO: use Phase.DEPENDENCIES_MONGO_DRIVER
            processorTarget.addDeploymentProcessor(MongoDriverExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_MONGO_DRIVER, DriverDependencyProcessor.getInstance());
        }
    }, OperationContext.Stage.RUNTIME);

    startMongoDriverSubsysteService(context);
}
 
Example 14
Project: wildfly-camel-examples   File: CxfWsCdiSecureExampleTest.java   View source code 6 votes vote down vote up
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
    ModelNode[] steps = new ModelNode[5];
    steps[0] = DMRUtils.createOpNode(ADDRESS_SUBSYSTEM_UNDERTOW_HTTPS_LISTENER, ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION);
    steps[0].get(ModelDescriptionConstants.NAME).set("verify-client");

    steps[1] = DMRUtils.createOpNode(ADDRESS_SUBSYSTEM_SECURITY_SECURITY_DOMAIN_CLIENT_CERT, ModelDescriptionConstants.REMOVE);

    steps[2] = DMRUtils.createOpNode(ADDRESS_SUBSYSTEM_SECURITY_SECURITY_DOMAIN_CERTIFICATE_TRUST_DOMAIN, ModelDescriptionConstants.REMOVE);

    steps[3] = DMRUtils.createOpNode(ADDRESS_SYSTEM_PROPERTY_TRUST_STORE, ModelDescriptionConstants.REMOVE);
    steps[4] = DMRUtils.createOpNode(ADDRESS_SYSTEM_PROPERTY_TRUST_STORE_PASSWORD, ModelDescriptionConstants.REMOVE);

    ModelNode compositeNode = DMRUtils.createCompositeNode(steps);
    managementClient.getControllerClient().execute(compositeNode);

    UserManager.removeApplicationUser(APPLICATION_USER);
    UserManager.revokeRoleFromApplicationUser(APPLICATION_USER, APPLICATION_ROLE);
}
 
Example 15
Project: wildfly-camel-examples   File: ServerReload.java   View source code 6 votes vote down vote up
private static void executeReload(ModelControllerClient client, boolean adminOnly) {
    ModelNode operation = new ModelNode();
    operation.get(OP_ADDR).setEmptyList();
    operation.get(OP).set("reload");
    operation.get("admin-only").set(adminOnly);
    try {
        ModelNode result = client.execute(operation);
        if (!"success".equals(result.get(ClientConstants.OUTCOME).asString())) {
            fail("Reload operation didn't finished successfully: " + result.asString());
        }
    } catch(IOException e) {
        final Throwable cause = e.getCause();
        if (!(cause instanceof ExecutionException) && !(cause instanceof CancellationException)) {
            throw new RuntimeException(e);
        } // else ignore, this might happen if the channel gets closed before we got the response
    }
}
 
Example 16
Project: smpp-extensions   File: SmppSubsystemParser.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
    PathAddress address = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SmppExtension.SUBSYSTEM_NAME));

    final ModelNode subsystem = new ModelNode();
    subsystem.get(OP).set(ADD);
    subsystem.get(OP_ADDR).set(address.toModelNode());
    list.add(subsystem);

    // mbean elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
        switch (Namespace.forUri(reader.getNamespaceURI())) {
            case SMPPEXT_1_0: {
                final String tagName = reader.getLocalName();
                if (tagName.equals(SmppMbeanDefinition.MBEAN)) {
                    parseMbean(reader, address, list);
                }
                break;
            }
            default: {
                throw unexpectedElement(reader);
            }
        }
    }
}
 
Example 17
Project: smpp-extensions   File: SubsystemAdd.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void performBoottime(OperationContext context, ModelNode operation, ModelNode model,
        ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers)
        throws OperationFailedException {

    ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));

    SmppService service = SmppService.INSTANCE;
    service.setModel(fullModel);

    ServiceName name = SmppService.getServiceName();
    ServiceController<SmppServiceInterface> controller = context.getServiceTarget()
            .addService(name, service)
            .addDependency(PathManagerService.SERVICE_NAME, PathManager.class, service.getPathManagerInjector())
            .addDependency(MBeanServerService.SERVICE_NAME, MBeanServer.class, service.getMbeanServer())
            .addListener(verificationHandler)
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .install();
    newControllers.add(controller);

}
 
Example 18
Project: wildfly-swarm   File: JdrArquillianTest.java   View source code 6 votes vote down vote up
@Test
@RunAsClient
public void testClient() throws Exception {
    ModelControllerClient client = ModelControllerClient.Factory.create(
            "localhost", 9990
    );

    ModelNode response = client.execute(
            Operations.createOperation("generate-jdr-report",
                                       Operations.createAddress("subsystem", "jdr")
            )
    );

    assertThat(response.get("outcome").asString()).isEqualTo("success");

    ModelNode result = response.get("result");

    String reportLocation = result.get("report-location").asString();

    assertThat(reportLocation).endsWith(".zip");
}
 
Example 19
Project: wildfly-swarm   File: CamelMarshaller.java   View source code 6 votes vote down vote up
@Override
public void marshal(List<ModelNode> list) {
    PathAddress subsystem = PathAddress.pathAddress("subsystem", "camel");

    Map<String, String> contexts = fraction.contexts();

    for (String key : contexts.keySet()) {
        String path = contexts.get(key);
        try {
            String value = read(path);
            PathAddress context = subsystem.append("context", key);
            ModelNode node = new ModelNode();
            node.get(OP).set(ADD);
            node.get(OP_ADDR).set(context.toModelNode());
            node.get(VALUE).set(value);
            list.add(node);
        } catch (ModuleLoadException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 20
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode getNodeInfo() {

    ModelNode op = new ModelNode();
    op.get(ADDRESS).setEmptyList();
    op.get(OP).set("query");
    op.get(SELECT).add("name");
    op.get(SELECT).add("server-state");
    op.get(SELECT).add("suspend-state");
    op.get(SELECT).add("running-mode");
    op.get(SELECT).add("uuid");

    try {
        ModelNode response = controllerClient.execute(op);
        ModelNode unwrapped = unwrap(response);
        unwrapped.get("swarm-version").set(SwarmInfo.VERSION);
        return unwrapped;
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }

}
 
Example 21
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode heap() {

    // /core-service=platform-mbean/type=memory:read-resource(include-runtime=true)

    ModelNode op = new ModelNode();
    op.get(ADDRESS).add("core-service", "platform-mbean");
    op.get(ADDRESS).add("type", "memory");
    op.get(OP).set("query");
    op.get(SELECT).add("heap-memory-usage");
    op.get(SELECT).add("non-heap-memory-usage");

    try {
        ModelNode response = controllerClient.execute(op);
        return unwrap(response);
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }
}
 
Example 22
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode threads() {

    // /core-service=platform-mbean/type=threading:read-resource(include-runtime=true)

    ModelNode op = new ModelNode();
    op.get(ADDRESS).add("core-service", "platform-mbean");
    op.get(ADDRESS).add("type", "threading");
    op.get(OP).set("query");
    op.get(SELECT).add("thread-count");
    op.get(SELECT).add("peak-thread-count");
    op.get(SELECT).add("total-started-thread-count");
    op.get(SELECT).add("current-thread-cpu-time");
    op.get(SELECT).add("current-thread-user-time");

    try {
        ModelNode response = controllerClient.execute(op);
        return unwrap(response);
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }
}
 
Example 23
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode getNodeInfo() {

    ModelNode op = new ModelNode();
    op.get(ADDRESS).setEmptyList();
    op.get(OP).set("query");
    op.get(SELECT).add("name");
    op.get(SELECT).add("server-state");
    op.get(SELECT).add("suspend-state");
    op.get(SELECT).add("running-mode");
    op.get(SELECT).add("uuid");

    try {
        ModelNode response = controllerClient.execute(op);
        ModelNode unwrapped = unwrap(response);
        unwrapped.get("swarm-version").set(SwarmInfo.VERSION);
        return unwrapped;
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }

}
 
Example 24
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode heap() {

    // /core-service=platform-mbean/type=memory:read-resource(include-runtime=true)

    ModelNode op = new ModelNode();
    op.get(ADDRESS).add("core-service", "platform-mbean");
    op.get(ADDRESS).add("type", "memory");
    op.get(OP).set("query");
    op.get(SELECT).add("heap-memory-usage");
    op.get(SELECT).add("non-heap-memory-usage");

    try {
        ModelNode response = controllerClient.execute(op);
        return unwrap(response);
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }
}
 
Example 25
Project: wildfly-swarm   File: MonitorService.java   View source code 6 votes vote down vote up
@Override
public ModelNode threads() {

    // /core-service=platform-mbean/type=threading:read-resource(include-runtime=true)

    ModelNode op = new ModelNode();
    op.get(ADDRESS).add("core-service", "platform-mbean");
    op.get(ADDRESS).add("type", "threading");
    op.get(OP).set("query");
    op.get(SELECT).add("thread-count");
    op.get(SELECT).add("peak-thread-count");
    op.get(SELECT).add("total-started-thread-count");
    op.get(SELECT).add("current-thread-cpu-time");
    op.get(SELECT).add("current-thread-user-time");

    try {
        ModelNode response = controllerClient.execute(op);
        return unwrap(response);
    } catch (IOException e) {
        return new ModelNode().get(FAILURE_DESCRIPTION).set(e.getMessage());
    }
}
 
Example 26
Project: wildfly-swarm   File: StandaloneXMLParser.java   View source code 6 votes vote down vote up
public StandaloneXMLParser() {

        parserDelegate = new StandaloneXml(new ExtensionHandler() {
            @Override
            public void parseExtensions(XMLExtendedStreamReader reader, ModelNode address, Namespace namespace, List<ModelNode> list) throws XMLStreamException {
                reader.discardRemainder(); // noop
            }

            @Override
            public Set<ProfileParsingCompletionHandler> getProfileParsingCompletionHandlers() {
                return Collections.emptySet();
            }

            @Override
            public void writeExtensions(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
                // noop
            }
        }, ParsingOption.IGNORE_SUBSYSTEM_FAILURES);

        xmlMapper = XMLMapper.Factory.create();

        addDelegate(new QName(Namespace.CURRENT.getUriString(), SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:4.1", SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:4.0", SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:2.0", SERVER), parserDelegate);
    }
 
Example 27
Project: wildfly-swarm   File: SocketBindingGroupMarshaller.java   View source code 6 votes vote down vote up
private void configureSocketBinding(PathAddress address, SocketBinding binding, List<ModelNode> list) {


        ModelNode node = new ModelNode();

        node.get(OP_ADDR).set(address.append("socket-binding", binding.name()).toModelNode());
        node.get(OP).set(ADD);
        node.get(PORT).set(new ValueExpression(binding.portExpression()));
        if (binding.iface() != null) {
            node.get(INTERFACE).set(binding.iface());
        }
        if (binding.multicastAddress() != null) {
            node.get(MULTICAST_ADDRESS).set(binding.multicastAddress());
        }
        if (binding.multicastPortExpression() != null) {
            node.get(MULTICAST_PORT).set(new ValueExpression(binding.multicastPortExpression()));
        }

        list.add(node);
    }
 
Example 28
Project: wildfly-swarm   File: ConfigViewPropertyMarshaller.java   View source code 6 votes vote down vote up
public void marshal(List<ModelNode> list) {
    Properties properties = this.configView.asProperties();
    Enumeration<?> names = properties.propertyNames();
    while (names.hasMoreElements()) {
        String key = (String) names.nextElement();
        if (!key.startsWith("jboss") && !key.startsWith("java")) {
            String value = properties.getProperty(key);
            if (value != null) {
                SwarmConfigMessages.MESSAGES.marshalProjectStageProperty(key);
                ModelNode modelNode = new ModelNode();
                modelNode.get(OP).set(ADD);
                modelNode.get(ADDRESS).set("system-property", key);
                modelNode.get(VALUE).set(properties.getProperty(key));
                list.add(modelNode);
            }
        }
    }
}
 
Example 29
Project: wildfly-swarm   File: XMLMarshaller.java   View source code 6 votes vote down vote up
protected void parse(URL url, Set<URL> seen, List<ModelNode> list) {
    if (url == null) {
        return;
    }
    if (seen.contains(url)) {
        return;
    }
    seen.add(url);
    try {
        List<ModelNode> subList = this.parser.parse(url);
        SwarmConfigMessages.MESSAGES.marshalXml(url.toExternalForm(), subList.toString());
        list.addAll(subList);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 30
Project: xtf   File: DockerInspect.java   View source code 5 votes vote down vote up
/**
 * Pulls given image to master and runs docker inspect command against it.
 * Result is stored and parsed by object methods.
 *
 * @param image image url to initialize new instance of this object
 * @return new instance
 */
public static DockerInspect from(String image) {
	log.info("Pulling image '{}' to master", image);
	OpenShiftNode.master().executeCommand("sudo docker pull " + image);

	final String result = OpenShiftNode.master().executeCommand("sudo docker inspect " + image);
	log.debug("Docker inspect result:\n'{}'", result);

	return new DockerInspect(ModelNode.fromJSONString(result).get(0));
}
 
Example 31
Project: xtf   File: YamlUtils.java   View source code 5 votes vote down vote up
public static ModelNode yaml2dmr(String yaml) throws IOException {
	ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
	Object obj = yamlMapper.readValue(yaml, Object.class);

	ObjectMapper jsonMapper = new ObjectMapper();
	String yamlAsJson = jsonMapper.writeValueAsString(obj);

	return ModelNode.fromJSONString(yamlAsJson);
}
 
Example 32
Project: xtf   File: YamlUtils.java   View source code 5 votes vote down vote up
public static String dmr2yaml(ModelNode modelNode) throws IOException {
	ObjectMapper jsonMapper = new ObjectMapper();
	ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());

	String jsonString = modelNode.toJSONString(false);
	Object obj = jsonMapper.readValue(jsonString, Object.class);

	return yamlMapper.writeValueAsString(obj);
}
 
Example 33
Project: xtf   File: Fabric8MavenWrapper.java   View source code 5 votes vote down vote up
public ModelNode getDeployment() {
	File jsonFile = projectPath.resolve(MANIFEST_PATH).toFile();
	ModelNode template = null;
	try {
		template = ModelNode.fromJSONStream(new FileInputStream(jsonFile));
		log.debug(template.toJSONString(false));
	} catch (IOException e) {
		Assert.fail("Failed to parse or access JSON: " + jsonFile.getAbsolutePath());
	}
	return template;
}
 
Example 34
Project: xtf   File: UsageRecorder.java   View source code 5 votes vote down vote up
public static void recordImage(String imagestream, String image) {
	if (INSTANCE.imageRecords.add(new ImageRecord(imagestream, image))) {
		ModelNode imageNode = INSTANCE.json.get("images").add();

		imageNode.get("image-stream").set(imagestream);
		imageNode.get("image").set(image);

		flush();
	}
}
 
Example 35
Project: xtf   File: UsageRecorder.java   View source code 5 votes vote down vote up
public static void recordTemplate(String name, String repository, String branch, String commitId) {
	if (INSTANCE.templateRecords.add(new TemplateRecord(name, repository, branch, commitId))) {
		ModelNode templateNode = INSTANCE.json.get("templates").add();

		templateNode.get("name").set(name);
		templateNode.get("repository").set(repository);
		templateNode.get("branch").set(branch);
		templateNode.get("commit").set(commitId);

		flush();
	}
}
 
Example 36
Project: xtf   File: UsageRecorder.java   View source code 5 votes vote down vote up
private UsageRecorder() {
	json = new ModelNode();
	json.get("versions").setEmptyObject();
	json.get("images").setEmptyList();
	json.get("templates").setEmptyList();
	json.get("properties").setEmptyList();

	jsonFile = IOUtils.findProjectRoot().resolve("usage.json");

	saveJson();
}
 
Example 37
Project: xtf   File: Recorder.java   View source code 5 votes vote down vote up
private static String getKubeDefaultVersion() {
	log.info("action=retrieve-kube-version status=START");
	try {
		final String version = HttpClient.get(TestConfiguration.masterUrl() + "/version").response();
		log.info("action=retrieve-kube-version status=FINISH");
		return ModelNode.fromJSONString(version).get("gitVersion").asString();
	} catch (IOException e) {
		log.info("action=retrieve-kube-version status=ERROR", e);
	}
	return VERSION_FALLBACK;
}
 
Example 38
Project: wildfly-microprofile-config   File: ConfigSourceProviderDefinition.java   View source code 5 votes vote down vote up
private static Class unwrapClass(ModelNode classModel) throws OperationFailedException {
    String className = classModel.get(NAME).asString();
    String moduleName = classModel.get(MODULE).asString();
    try {
        ModuleIdentifier moduleID = ModuleIdentifier.fromString(moduleName);
        Module module = Module.getCallerModuleLoader().loadModule(moduleID);
        Class<?> clazz = module.getClassLoader().loadClass(className);
        return clazz;
    } catch (Exception e) {
        throw ROOT_LOGGER.unableToLoadClassFromModule(className, moduleName);
    }
}
 
Example 39
Project: wildfly-microprofile-config   File: ConfigSourceDefinition.java   View source code 5 votes vote down vote up
private static Class unwrapClass(ModelNode classModel) throws OperationFailedException {
    String className = classModel.get(NAME).asString();
    String moduleName = classModel.get(MODULE).asString();
    try {
        ModuleIdentifier moduleID = ModuleIdentifier.fromString(moduleName);
        Module module = Module.getCallerModuleLoader().loadModule(moduleID);
        Class<?> clazz = module.getClassLoader().loadClass(className);
        return clazz;
    } catch (Exception e) {
        throw ROOT_LOGGER.unableToLoadClassFromModule(className, moduleName);
    }
}
 
Example 40
Project: wildfly-microprofile-health   File: HealthHttpHandler.java   View source code 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
   Collection<HealthCheckResponse> responses = monitor.check();
   ModelNode result = CheckOperation.computeResult(responses);
   MicroProfileHealthLogger.ROOT_LOGGER.debugf("checking health check: %s", result.toJSONString(true));
   exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
   boolean ok = result.get("outcome").asString() == UP.toString();
   final int statusCode = ok ? 200 : 503;
   exchange.setStatusCode(statusCode)
           .getResponseSender().send(result.toJSONString(true));
}