Java Code Examples for org.jboss.as.controller.client.ModelControllerClient#execute()

The following examples show how to use org.jboss.as.controller.client.ModelControllerClient#execute() . 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: JdrArquillianTest.java    From thorntail with Apache License 2.0 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 2
Source File: Util.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isDeploymentPresent(String name, ModelControllerClient client, String serverGroup) throws OperationFormatException {
    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();

    builder.addNode(Util.SERVER_GROUP, serverGroup);
    builder.addNode(Util.DEPLOYMENT, name);
    builder.setOperationName(Util.READ_RESOURCE);
    ModelNode request = builder.buildRequest();
    try {
        ModelNode outcome = client.execute(request);
        if (isSuccess(outcome)) {
            return outcome.hasDefined(RESULT);
        }
    } catch (Exception ex) {
        return false;
    }

    return false;
}
 
Example 3
Source File: ServerAuthenticationTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean lookupHostInModel(final ModelControllerClient client, final String host) throws Exception {
    final ModelNode operation = new ModelNode();
    operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
    operation.get(OP_ADDR).add(HOST, host);
    operation.get(NAME).set(HOST_STATE);

    try {
        final ModelNode result = client.execute(operation);
        if (result.get(OUTCOME).asString().equals(SUCCESS)){
            final ModelNode model = result.require(RESULT);
            if (model.asString().equalsIgnoreCase("running")) {
                return true;
            }
        }
    } catch (IOException e) {
        //
    }
    return false;
}
 
Example 4
Source File: CLIEmbedServerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tests accessing a ModelControllerClient from the cli, and using it to deploy with the de
 * deployment content attached as a stream.
 */
@Test
public void testModelControllerDeploy() throws Exception {
    validateServerConnectivity();

    ModelNode opNode = new ModelNode();
    opNode.get(OP).set(ADD);
    opNode.get(OP_ADDR).add(DEPLOYMENT, SERVICE_ACTIVATOR_DEPLOYMENT_NAME);
    opNode.get(ENABLED).set(true);
    ModelNode content = opNode.get(CONTENT).add();
    content.get(INPUT_STREAM_INDEX).set(0);

    InputStream is = serviceActivatorDeployment.as(ZipExporter.class).exportAsInputStream();
    Operation op = Operation.Factory.create(opNode, Collections.singletonList(is), true);

    ModelControllerClient mcc = cli.getCommandContext().getModelControllerClient();
    ModelNode response = mcc.execute(op);
    assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());

    // We could use the CLI to do this, but since we have the MCC and the code already exists, re-use it
    ServiceActivatorDeploymentUtil.validateProperties(mcc);
}
 
Example 5
Source File: AbstractControllerService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void executeRestartNormalServer(ModelControllerClient client) {
    try {
        ModelNode shutdown = Util.createOperation(SHUTDOWN, PathAddress.EMPTY_ADDRESS);
        shutdown.get(RESTART).set(true);
        // Since we cannot clear system properties for a shutdown, we write a marker here to
        // skip running the cli script again
        Files.createFile(restartInitiated.toPath());

        ROOT_LOGGER.restartingServerAfterBootCliScript(restartInitiated, CLI_SCRIPT_PROPERTY, SKIP_RELOAD_PROPERTY, MARKER_DIRECTORY_PROPERTY);

        ModelNode result = client.execute(shutdown);
        if (result.get(OUTCOME).asString().equals(FAILED)) {
            throw new RuntimeException(result.get(FAILURE_DESCRIPTION).asString());
        }
    } catch (IOException e) {
        try {
            deleteFile(restartInitiated);
        } catch (IOException ex) {
            e = ex;
        }
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: InterfaceManagementUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ModelNode executeForResult(final ModelControllerClient client, final ModelNode operation) {
    try {
        final ModelNode result = client.execute(operation);
        if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
            return result.get("result");
        } else {
            Assert.fail("Operation outcome is " + result.get("outcome").asString() + " " + result.get("failure-description"));
            throw new RuntimeException(); // not reached
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: AbstractTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Boolean apply(final EmbeddedManagedProcess server) {

    try {
        final ModelControllerClient client = server.getModelControllerClient();
        final ModelNode result = client.execute(op);
        if (Operations.isSuccessfulOutcome(result) &&
                ClientConstants.CONTROLLER_PROCESS_STATE_RUNNING.equals(Operations.readResult(result).asString())) {
            return true;
        }
    } catch (IllegalStateException | IOException ignore) {
    }
    return false;
}
 
Example 8
Source File: MyDeployer.java    From wildfly-samples with MIT License 5 votes vote down vote up
private void readDataSources(ModelControllerClient client) throws IOException {
    ModelNode op = new ModelNode();
    op.get("operation").set("read-resource");

    ModelNode address = op.get("address");
    address.add("subsystem", "datasources");

    ModelNode returnVal = client.execute(op);
    System.out.println(returnVal.get("result").toString());
}
 
Example 9
Source File: ReadAttributeGroupTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void createResource() throws IOException {
    ModelControllerClient client = getManagementClient().getControllerClient();
    ModelNode op = createOpNode(TEST_DS, ADD);
    op.get("connection-url").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    op.get("jndi-name").set("java:jboss/datasources/TestDS");
    op.get("driver-name").set("h2");
    op.get("password").set("sa");
    op.get("security-domain").set("other");
    ModelNode result = client.execute(op);
    assertEquals(result.asString(), SUCCESS, result.get(OUTCOME).asString());
}
 
Example 10
Source File: DeploymentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void cleanUp(String deployment) {
    ModelNode op = new ModelNode();
    op.get(OP).set(READ_RESOURCE_OPERATION);
    op.get(OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, deployment);
    ModelControllerClient client = managementClient.getControllerClient();
    ModelNode result;
    try {
        result = client.execute(op);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (result != null && Operations.isSuccessfulOutcome(result)) {
        ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client);
        Future<?> future = manager.execute(manager.newDeploymentPlan()
                .undeploy(deployment)
                .remove(deployment)
                .build());

        awaitDeploymentExecution(future);
    }

    String jbossBaseDir = System.getProperty("jboss.home");
    Assert.assertNotNull(jbossBaseDir);
    Path dataDir = new File(jbossBaseDir).toPath().resolve("standalone").resolve("data");
    if (Files.exists(dataDir)) { cleanFile(dataDir.resolve("managed-exploded").toFile()); }
    File archivesDir = new File("target", "archives");
    if (Files.exists(archivesDir.toPath())) { cleanFile(archivesDir); }
}
 
Example 11
Source File: BootableJar.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void waitAndClean() {
    try {
        // Give max 10 seconds for the server to stop before to delete jbossHome.
        ModelNode mn = new ModelNode();
        mn.get(ADDRESS);
        mn.get(OP).set(READ_ATTRIBUTE_OPERATION);
        mn.get(NAME).set(SERVER_STATE);
        for (int i = 0; i < 10; i++) {
            try {
                ModelControllerClient client = server.getModelControllerClient();
                if (client != null) {
                    ModelNode ret = client.execute(mn);
                    if (ret.hasDefined(RESULT)) {
                        String val = ret.get(RESULT).asString();
                        if (STOPPED.equals(val)) {
                            log.serverStopped();
                            break;
                        } else {
                            log.serverNotStopped();
                        }
                    }
                    Thread.sleep(1000);
                } else {
                    log.nullController();
                    break;
                }
            } catch (Exception ex) {
                log.unexpectedExceptionWhileShuttingDown(ex);
            }
        }
    } finally {
        cleanup();
    }
}
 
Example 12
Source File: RemoveManagementInterfaceTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void serverTearDown() throws Exception {
    ModelControllerClient client = getNativeModelControllerClient();
    ModelNode operation = createOpNode("socket-binding-group=standard-sockets/socket-binding=management-http", ModelDescriptionConstants.READ_RESOURCE_OPERATION);
    ModelNode response = client.execute(operation);
    if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
        // add http-management socket binding
        operation = createOpNode("socket-binding-group=standard-sockets/socket-binding=management-http", ModelDescriptionConstants.ADD);
        operation.get("port").set(MANAGEMENT_HTTP_PORT);
        operation.get("interface").set("management");
        CoreUtils.applyUpdate(operation, client);
    }
    operation = createOpNode("core-service=management/management-interface=http-interface", ModelDescriptionConstants.READ_RESOURCE_OPERATION);
    response = client.execute(operation);
    if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
        // create http interface to control server
        operation = createOpNode("core-service=management/management-interface=http-interface", ModelDescriptionConstants.ADD);
        final ModelNode httpUpgrade = new ModelNode().setEmptyObject();
        httpUpgrade.get("enabled").set(true);
        if (saslAuthFactory != null) {
            httpUpgrade.get("sasl-authentication-factory").set(saslAuthFactory);
        } else {
            operation.get("security-realm").set(securityRealm);
        }
        operation.get("socket-binding").set("management-http");
        operation.get("http-upgrade").set(httpUpgrade);
        CoreUtils.applyUpdate(operation, client);
    }
    // To recreate http interface, a reload of server is required
    ServerReload.executeReloadAndWaitForCompletion(getNativeModelControllerClient(), TimeoutUtil.adjust(30000), false, "remote", TestSuiteEnvironment.getServerAddress(), MANAGEMENT_NATIVE_PORT);
    client = getHttpModelControllerClient();
    //Remove native interface
    try {
        operation = createOpNode("core-service=management/management-interface=native-interface", ModelDescriptionConstants.REMOVE);
        CoreUtils.applyUpdate(operation, client);
        operation = createOpNode("socket-binding-group=standard-sockets/socket-binding=management-native", ModelDescriptionConstants.REMOVE);
        CoreUtils.applyUpdate(operation, client);
    } finally {
        safeCloseClient(client);
    }
}
 
Example 13
Source File: DeploymentOverlayHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected ModelNode loadLinkResources(final ModelControllerClient client, String overlay, String serverGroup) throws CommandLineException {
    final ModelNode op = new ModelNode();
    final ModelNode addr = op.get(Util.ADDRESS);
    if(serverGroup != null) {
        addr.add(Util.SERVER_GROUP, serverGroup);
    }
    addr.add(Util.DEPLOYMENT_OVERLAY, overlay);
    op.get(Util.OPERATION).set(Util.READ_CHILDREN_RESOURCES);
    op.get(Util.CHILD_TYPE).set(Util.DEPLOYMENT);
    final ModelNode response;
    try {
        response = client.execute(op);
    } catch (IOException e) {
        throw new CommandLineException("Failed to load the list of deployments for overlay " + overlay, e);
    }

    final ModelNode result = response.get(Util.RESULT);
    if(!result.isDefined()) {
        final String descr = Util.getFailureDescription(response);
        if(descr != null && (descr.contains("WFLYCTL0216") || descr.contains("WFLYCTL0202"))) {
            // resource doesn't exist
            return null;
        }
        throw new CommandLineException("Failed to load the list of deployments for overlay " + overlay + ": " + response);
    }
    return result;
}
 
Example 14
Source File: ExtensionManagementTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void removeIgnoreFailure(ModelControllerClient client, PathAddress subsystemAddress) throws Exception {
    try {
        ModelNode op = Util.createRemoveOperation(subsystemAddress);
        client.execute(op);
    } catch (Exception ignore) {

    }
}
 
Example 15
Source File: ReloadHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doHandleEmbedded(CommandContext ctx, ModelControllerClient client) throws CommandLineException {

        assert(embeddedServerRef != null);
        assert(embeddedServerRef.get() != null);

        final ModelNode op = this.buildRequestWithoutHeaders(ctx);
        if (embeddedServerRef.get().isHostController()) {
            // WFCORE-938
            // for embedded-hc, we require --admin-only=true to be passed until the EHC supports --admin-only=false
            if (!isAdminOnly(ctx)) {
                throw new CommandLineException("Reload into running mode is not supported, --admin-only must be specified.");
            }
        }

        try {
            final ModelNode response = client.execute(op);
            if(!Util.isSuccess(response)) {
                throw new CommandLineException(Util.getFailureDescription(response));
            }
        } catch(IOException e) {
            // This shouldn't be possible, as this is a local client
            StreamUtils.safeClose(client);
            throw new CommandLineException("Failed to execute :reload", e);
        }

        ensureServerRebootComplete(ctx, client);
    }
 
Example 16
Source File: ServerConfigurator.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void executeOperation(final ModelControllerClient client, final Operation op) throws IOException {
    final ModelNode result = client.execute(op);
    if (!Operations.isSuccessfulOutcome(result)) {
        Assert.fail(Operations.getFailureDescription(result).asString());
    }
}
 
Example 17
Source File: DisableLocalAuthServerSetupTask.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void setup(final ManagementClient managementClient) throws Exception {

    final ModelControllerClient client = managementClient.getControllerClient();
    final Operations.CompositeOperationBuilder compositeOp = Operations.CompositeOperationBuilder.create();

    // Add the socket binding for the native-interface
    ModelNode op = Operations.createAddOperation(nativeSocketBindingAddress);
    op.get("port").set(9999);
    op.get("interface").set("management");
    compositeOp.addStep(op.clone());

    // Add the native-interface
    compositeOp.addStep(Operations.createAddOperation(nativeSecurityRealmAddress));

    // Add the native-interface local authentication
    final ModelNode nativeRealmLocalAuthAddress = nativeSecurityRealmAddress.clone().add("authentication", "local");
    op = Operations.createAddOperation(nativeRealmLocalAuthAddress);
    op.get("default-user").set("$local");
    compositeOp.addStep(op.clone());

    // Add the native interface
    op = Operations.createAddOperation(nativeInterfaceAddress);
    op.get("security-realm").set("native-realm");
    op.get("socket-binding").set("management-native");
    compositeOp.addStep(op.clone());

    // Undefine Elytron local-auth
    op = Operations.createReadResourceOperation(saslFactoryAddress);
    ModelNode result = client.execute(op);
    if (Operations.isSuccessfulOutcome(result)) {
        op = Operations.createOperation("map-remove", saslFactoryAddress);
        op.get("name").set("properties");
        op.get("key").set(defaultUserKey);
        compositeOp.addStep(op.clone());
    }

    // Undefine the legacy local-auth
    op = Operations.createReadResourceOperation(managementRealmAddress);
    result = client.execute(op);
    if (Operations.isSuccessfulOutcome(result)) {
        compositeOp.addStep(Operations.createUndefineAttributeOperation(managementRealmAddress, "default-user"));

    }

    executeForSuccess(client, compositeOp.build());

    // Use the current client to execute the reload, but the native client to ensure the reload is complete
    ServerReload.executeReloadAndWaitForCompletion(client, ServerReload.TIMEOUT, false, protocol, host, port);
}
 
Example 18
Source File: AdminOnlyModeTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private ModelNode executeForResult(final ModelControllerClient client, final ModelNode operation) throws IOException {
    final ModelNode result = client.execute(operation);
    return validateResponse(result);
}
 
Example 19
Source File: CLIAccessControl.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static ModelNode getAccessControl(ModelControllerClient client, String[] parent, OperationRequestAddress address, boolean operations) {

        if(client == null) {
            return null;
        }

        if(address.endsOnType()) {
            log.debug("The prefix ends on a type.");
            return null;
        }

        final ModelNode request = new ModelNode();
        setAddress(request, parent, address);
        request.get(Util.OPERATION).set(Util.READ_RESOURCE_DESCRIPTION);
        request.get(Util.ACCESS_CONTROL).set(Util.TRIM_DESCRIPTIONS);
        if(operations) {
            request.get(Util.OPERATIONS).set(true);
        }

        final ModelNode response;
        try {
            response = client.execute(request);
        } catch (Exception e) {
            log.warnf(e, "Failed to execute %s", Util.READ_RESOURCE_DESCRIPTION);
            return null;
        }

        if (!Util.isSuccess(response)) {
            log.debugf("Failed to execute %s:%s", Util.READ_RESOURCE_DESCRIPTION, response);
            return null;
        }

        if(!response.has(Util.RESULT)) {
            log.warnf("Response is missing result for %s:%s", Util.READ_RESOURCE_DESCRIPTION, response);
            return null;
        }

        final ModelNode result = response.get(Util.RESULT);
        if(!result.has(Util.ACCESS_CONTROL)) {
            log.warnf("Result is missing access-control for %s:%s", Util.READ_RESOURCE_DESCRIPTION, response);
            return null;
        }

        return result.get(Util.ACCESS_CONTROL);
    }
 
Example 20
Source File: NativeApiPatchingTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Apply a simple one-off patch through the native API.
 * Roll it back.
 *
 * @throws Exception
 */
@Test
public void testApplyOneoff() throws Exception {
    logger.trace("APPLYING ONEOFF:)");
    ModelControllerClient client = getControllerClient();

    final String fileContent = "Hello World!";
    // prepare the patch
    String patchID = randomString();
    File oneOffPatchDir = mkdir(tempDir, patchID);
    String[] miscFileLocation = new String[]{"newPatchDirectory", "awesomeFile"};
    ContentModification miscFileAdded = ContentModificationUtils.addMisc(oneOffPatchDir, patchID,
            fileContent, miscFileLocation);
    ProductConfig productConfig = new ProductConfig(PRODUCT, AS_VERSION, "main");
    Patch oneOffPatch = PatchBuilder.create()
            .setPatchId(patchID)
            .setDescription("A one-off patch adding a misc file.")
            .oneOffPatchIdentity(productConfig.getProductName(), productConfig.getProductVersion())
            .getParent()
            .addContentModification(miscFileAdded)
            .build();
    createPatchXMLFile(oneOffPatchDir, oneOffPatch);
    File zippedPatch = createZippedPatchFile(oneOffPatchDir, patchID);

    controller.start();
    Operation o = NativeApiUtilsForPatching.createPatchOperation(zippedPatch);

    logger.trace(o.getOperation().toJSONString(false));
    ModelNode ret = client.execute(o);
    logger.trace(ret.toJSONString(false));
    Assert.assertTrue(ret.get("outcome").asString().equalsIgnoreCase("success"));

    controller.stop();

    controller.start();
    String path = AS_DISTRIBUTION + FILE_SEPARATOR + Joiner.on(FILE_SEPARATOR)
            .join(miscFileLocation);
    Assert.assertTrue("File " + path + " should exist", new File(path).exists());

    Assert.assertTrue("The patch " + patchID + " should be listed as installed",
            NativeApiUtilsForPatching.getInstalledPatches(client).contains(patchID));

    ModelNode itemForPatch = NativeApiUtilsForPatching.getHistoryItemForOneOffPatch(client, patchID);
    Assert.assertNotNull("The patch should appear in patching history", itemForPatch);

    Assert.assertEquals("Unexpected contents of misc file", fileContent, readFile(path));

    o = NativeApiUtilsForPatching.createRollbackOperation(patchID);
    logger.trace(o.getOperation().toJSONString(false));
    ret = client.execute(o);
    logger.trace(ret.toJSONString(false));
    //
    Assert.assertEquals(ret.get("outcome").asString(), "success");

    controller.stop();

    controller.start();

    Assert.assertFalse("File + " + path + " should have been deleted", new File(path).exists());

    Assert.assertFalse("The patch " + patchID + " NOT should be listed as installed",
            NativeApiUtilsForPatching.getInstalledPatches(client).contains(patchID));

    IoUtils.recursiveDelete(tempDir);
    IoUtils.recursiveDelete(zippedPatch);
}