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

The following examples show how to use org.jboss.dmr.ModelNode#has() . 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: DiscardUndefinedAttributesTransformer.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Set<String> checkModelNode(ModelNode modelNode) {

        Set<String> problems = null;
        for (String attr : attributeNames) {
            if (modelNode.has(attr)) {
                if (modelNode.hasDefined(attr)) {
                    if (problems == null) {
                        problems = new HashSet<String>();
                    }
                    problems.add(attr);
                } else {
                    modelNode.remove(attr);
                }
            }
        }
        return problems;
    }
 
Example 2
Source File: DomainControllerWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    super.execute(context, operation);
    final ModelNode model = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS).getModel();
    ModelNode dc = model.get(DOMAIN_CONTROLLER);
    if (operation.hasDefined(VALUE, LOCAL)) {
        dc.get(LOCAL).setEmptyObject();
        if (dc.has(REMOTE)) {
            dc.remove(REMOTE);
        }
        if (context.isBooting()) {
            initializeLocalDomain(null);
        }
    } else if (operation.hasDefined(VALUE, REMOTE)) {
        if (dc.has(LOCAL)) {
            dc.remove(LOCAL);
        }
        final ModelNode remoteDC = dc.get(REMOTE);
        secureRemoteDomain(context, operation, remoteDC);
        if (context.isBooting()) {
            initializeRemoteDomain(context, remoteDC);
        }
    }
}
 
Example 3
Source File: DeploymentsXml.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
static void writeContentItem(final XMLExtendedStreamWriter writer, final ModelNode contentItem)
        throws XMLStreamException {
    if (contentItem.has(HASH)) {
        WriteUtils.writeElement(writer, Element.CONTENT);
        WriteUtils.writeAttribute(writer, Attribute.SHA1, HashUtil.bytesToHexString(contentItem.require(HASH).asBytes()));
        DeploymentAttributes.CONTENT_ARCHIVE.getMarshaller().marshallAsAttribute(DeploymentAttributes.CONTENT_ARCHIVE, contentItem, true, writer);
        writer.writeEndElement();
    } else {
        if (contentItem.require(ARCHIVE).asBoolean()) {
            WriteUtils.writeElement(writer, Element.FS_ARCHIVE);
        } else {
            WriteUtils.writeElement(writer, Element.FS_EXPLODED);
        }
        WriteUtils.writeAttribute(writer, Attribute.PATH, contentItem.require(PATH).asString());
        if (contentItem.has(RELATIVE_TO))
            WriteUtils.writeAttribute(writer, Attribute.RELATIVE_TO, contentItem.require(RELATIVE_TO).asString());
        writer.writeEndElement();
    }
}
 
Example 4
Source File: ObjectTypeAttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected ModelNode convertParameterExpressions(ModelNode parameter) {
    ModelNode result = parameter;
    if (parameter.isDefined()) {
        boolean changeMade = false;
        ModelNode updated = new ModelNode().setEmptyObject();
        for (AttributeDefinition ad : valueTypes) {
            String fieldName = ad.getName();
            if (parameter.has(fieldName)) {
                ModelNode orig = parameter.get(fieldName);
                if (!orig.isDefined()) {
                    updated.get(fieldName); // establish undefined
                } else {
                    ModelNode converted = ad.convertParameterExpressions(orig);
                    changeMade |= !orig.equals(converted);
                    updated.get(fieldName).set(converted);
                }
            }
        }

        if (changeMade) {
            result = updated;
        }
    }
    return result;
}
 
Example 5
Source File: JmxManagementInterface.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ObjectName objectName(ModelNode operation) throws MalformedObjectNameException {
    StringBuilder builder = new StringBuilder();
    String opName = operation.get(OP).asString();
    if (operation.has(OP_ADDR)) {
        ModelNode address = operation.get(OP_ADDR);
        Iterator<ModelNode> it = address.asList().iterator();
        while (it.hasNext()) {
            Property segment = it.next().asProperty();
            if (opName.equals(ADD) && !it.hasNext()) { // skip the last one in case of 'add'
                continue;
            }
            builder.append(segment.getName()).append("=").append(segment.getValue().asString()).append(",");
        }
    }
    if (builder.toString().isEmpty()) {
        builder.append("management-root=server,");
    }

    builder.deleteCharAt(builder.length() - 1);
    return new ObjectName(domain + ":" + builder.toString());
}
 
Example 6
Source File: KeycloakAdapterConfigService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getValueOfAddrElement(ModelNode address, String elementName) {
    for (ModelNode element : address.asList()) {
        if (element.has(elementName)) return element.get(elementName).asString();
    }

    return null;
}
 
Example 7
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public final void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    final String name = context.getCurrentAddressValue();
    final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(name);
    if (configuration == null) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.handlerConfigurationNotFound(name));
    }
    final AttributeDefinition[] attributes = getAttributes();
    if (attributes != null) {
        boolean restartRequired = false;
        boolean reloadRequired = false;
        for (AttributeDefinition attribute : attributes) {
            // Only update if the attribute is on the operation
            if (operation.has(attribute.getName())) {
                handleProperty(attribute, context, model, logContextConfiguration, configuration);
                restartRequired = restartRequired || Logging.requiresRestart(attribute.getFlags());
                reloadRequired = reloadRequired || Logging.requiresReload(attribute.getFlags());
            }
        }
        if (restartRequired) {
            context.restartRequired();
        } else if (reloadRequired) {
            context.reloadRequired();
        }
    }

    // It's important that properties are written in the correct order, reorder the properties if
    // needed before the commit.
    addOrderPropertiesStep(context, propertySorter, configuration);
}
 
Example 8
Source File: LegacyConfigurationChangeResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks if the calling user may execute the operation. If he can then he cvan see it in the result.
 *
 * @param context
 * @param configurationChange
 * @throws OperationFailedException
 */
private void secureHistory(OperationContext context, ModelNode configurationChange) throws OperationFailedException {
    if (configurationChange.has(OPERATIONS)) {
        List<ModelNode> operations = configurationChange.get(OPERATIONS).asList();
        ModelNode authorizedOperations = configurationChange.get(OPERATIONS).setEmptyList();
        for (ModelNode operation : operations) {
            authorizedOperations.add(secureOperation(context, operation));
        }
    }
}
 
Example 9
Source File: CoreModelTestDelegate.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void adjustLocalDomainControllerWriteForHost(List<ModelNode> bootOperations) {
    //Remove the write-local-domain-controller operation since the test controller already simulates what it does at runtime.
    //For model validation to work, it always needs to be part of the model, and will be added there by the test controller.
    //We need to keep track of if it was part of the boot ops or not. If it was not part of the boot ops, the model will need
    //'sanitising' to remove it otherwise the xml comparison checks will fail.
    boolean dcInBootOps = false;
    for (Iterator<ModelNode> it = bootOperations.iterator() ; it.hasNext() ; ) {
        ModelNode op = it.next();
        String opName = op.get(OP).asString();
        if (opName.equals(LocalDomainControllerAddHandler.OPERATION_NAME) || opName.equals(RemoteDomainControllerAddHandler.OPERATION_NAME)) {
            dcInBootOps = true;
            break;
        }
        if(WRITE_ATTRIBUTE_OPERATION.equals(opName)) {
            String attributeName = op.get(NAME).asString();
            if(DOMAIN_CONTROLLER.equals(attributeName)) {
                dcInBootOps = true;
                break;
            }
        }
        // host=foo:add(), always has IS_DOMAIN_CONTROLLER defined.
        if(HostAddHandler.OPERATION_NAME.equals(opName) && op.has(IS_DOMAIN_CONTROLLER)
                && !op.get(IS_DOMAIN_CONTROLLER).equals(new ModelNode().setEmptyObject())) {
            dcInBootOps = true;
            break;
        }
    }
    if (!dcInBootOps) {
        testParser.addModelWriteSanitizer(new ModelWriteSanitizer() {
            @Override
            public ModelNode sanitize(ModelNode model) {
                if (model.isDefined() && model.has(DOMAIN_CONTROLLER)) {
                    model.remove(DOMAIN_CONTROLLER);
                }
                return model;
            }
        });
    }
}
 
Example 10
Source File: CliUtilsForPatching.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static boolean rollbackAll(CLIWrapper cli, String patchStream) {
    final String infoCommand = "patch info --patch-stream=%s --distribution=%s --json-output";
    final String rollbackCommand = "patch rollback --patch-stream=%s --patch-id=%s --distribution=%s --reset-configuration=true";
    boolean success = true;
    boolean doRollback = true;
    while (doRollback) {
        doRollback = false;
        String command = String.format(infoCommand, patchStream, PatchingTestUtil.AS_DISTRIBUTION);
        logger.debug("----- sending command to CLI: " + command + " -----");
        cli.sendLine(command);
        String response = cli.readOutput();
        ModelNode responseNode = ModelNode.fromJSONString(response);
        ModelNode result = responseNode.get("result");
        if (result.has("patches")) {
            final List<ModelNode> patchesList = result.get("patches").asList();
            if (!patchesList.isEmpty()) {
                doRollback = true;
                for (ModelNode n : patchesList) {
                    command = String.format(rollbackCommand, patchStream, n.asString(), PatchingTestUtil.AS_DISTRIBUTION);
                    logger.debug("----- sending command to CLI: " + command + " -----");
                    success = success && cli.sendLine(command, true);
                }
            }
        }
        if (result.has("cumulative-patch-id")) {
            final String cumulativePatchId = result.get("cumulative-patch-id").asString();
            if (!cumulativePatchId.equalsIgnoreCase(BASE)) {
                doRollback = true;
                command = String.format(rollbackCommand, patchStream, cumulativePatchId, PatchingTestUtil.AS_DISTRIBUTION);
                logger.debug("----- sending command to CLI: " + command + " -----");
                success = success && cli.sendLine(command, true);
            }
        }
    }
    return success;
}
 
Example 11
Source File: ModelNodePathOperand.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Object resolveValue(CommandContext ctx, ModelNode response) throws CommandLineException {
    ModelNode targetValue = response;
    for(String name : path) {
        if(!targetValue.has(name)) {
            return null;
        } else {
            targetValue = targetValue.get(name);
        }
    }
    return targetValue == null ? null : targetValue;
}
 
Example 12
Source File: AbstractCoreModelTest.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ModelNode fixSensitivityConstraint(ModelNode modelNode) {
    if (modelNode.hasDefined("core-service","management","access","authorization","constraint","sensitivity-classification","type")) {
        ModelNode typeNode = modelNode.get("core-service","management","access","authorization","constraint","sensitivity-classification","type");
        for (String type : typeNode.keys()) {
            if (typeNode.hasDefined(type, "classification")) {
                ModelNode classificationNode = typeNode.get(type, "classification");
                if ("core".equals(type)) {
                    if (!classificationNode.hasDefined("credential") || !classificationNode.hasDefined("domain-controller")) {
                        throw new IllegalArgumentException(classificationNode.toString());
                    }
                }
                for (String classification : classificationNode.keys()) {
                    ModelNode target = classificationNode.get(classification);
                    if (target.has("default-requires-addressable")) {
                        target.remove("default-requires-addressable");
                    }
                    if (target.has("default-requires-read")) {
                        target.remove("default-requires-read");
                    }
                    if (target.has("default-requires-write")) {
                        target.remove("default-requires-write");
                    }
                }
                if ("core".equals(type)) {
                    if (!classificationNode.hasDefined("credential") || !classificationNode.hasDefined("domain-controller")) {
                        throw new IllegalArgumentException(classificationNode.toString());
                    }
                }
            }
        }
    } else throw new IllegalArgumentException(modelNode.toString());
    return modelNode;
}
 
Example 13
Source File: SecurityCommandsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testInteractiveFailure() throws Exception {
    // Remove management-https
    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
    builder.setOperationName(Util.READ_RESOURCE);
    builder.addNode(Util.SOCKET_BINDING_GROUP, Util.STANDARD_SOCKETS);
    builder.addNode(Util.SOCKET_BINDING, Util.MANAGEMENT_HTTPS);
    ModelNode response = ctx.getModelControllerClient().execute(builder.buildRequest());
    ModelNode resource = null;
    if (Util.isSuccess(response)) {
        if (response.hasDefined(Util.RESULT)) {
            resource = response.get(Util.RESULT);
        }
    }
    if (resource == null) {
        throw new Exception("can't retrieve management-https");
    }
    ctx.handle("/socket-binding-group=standard-sockets/socket-binding=management-https:remove");
    try {
        CliProcessWrapper cli = new CliProcessWrapper().
                addJavaOption("-Duser.home=" + temporaryUserHome.getRoot().toPath().toString()).
                addCliArgument("--controller=remote+http://"
                        + TestSuiteEnvironment.getServerAddress() + ":"
                        + TestSuiteEnvironment.getServerPort()).
                addCliArgument("--connect");
        cli.executeInteractive();
        cli.clearOutput();
        Assert.assertTrue(cli.pushLineAndWaitForResults("security enable-ssl-management --interactive --no-reload", "Key-store file name"));
        Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_FILE_NAME, "Password"));
        Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_PASSWORD, "What is your first and last name? [Unknown]"));

        Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organizational unit? [Unknown]"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organization? [Unknown]"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your City or Locality? [Unknown]"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your State or Province? [Unknown]"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the two-letter country code for this unit? [Unknown]"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct y/n [y]"));

        Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Validity"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("", "Alias"));
        Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_ALIAS, "Enable SSL Mutual Authentication"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("n", "Do you confirm"));
        Assert.assertTrue(cli.pushLineAndWaitForResults("y", null));
        // Nothing was generated due to missing management-https
        assertEmptyModel(null);
        // check that the server is not in reload state
        builder = new DefaultOperationRequestBuilder();
        builder.setOperationName(Util.READ_RESOURCE);
        response = ctx.getModelControllerClient().execute(builder.buildRequest());
        if (response.has(Util.RESPONSE_HEADERS)) {
            ModelNode mn = response.get(Util.RESPONSE_HEADERS);
            if (mn.has("process-state")) {
                ModelNode ps = mn.get("process-state");
                if ("reload-required".equals(ps.asString())) {
                    throw new Exception("Server is in reload state");
                }
            }
        }
    } finally {
        try {
            builder = new DefaultOperationRequestBuilder();
            builder.setOperationName(Util.ADD);
            builder.addNode(Util.SOCKET_BINDING_GROUP, Util.STANDARD_SOCKETS);
            builder.addNode(Util.SOCKET_BINDING, Util.MANAGEMENT_HTTPS);
            builder.getModelNode().get("port").set(resource.get("port"));
            builder.getModelNode().get("interface").set(resource.get("interface"));
            response = ctx.getModelControllerClient().execute(builder.buildRequest());
            if (!Util.isSuccess(response)) {
                throw new Exception("Failure adding back management-https");
            }
        } finally {
            ctx.handle("reload");
        }
    }
}
 
Example 14
Source File: OperationCoordinatorStepHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void executeTwoPhaseOperation(OperationContext context, ModelNode operation, OperationRouting routing) throws OperationFailedException {

        HOST_CONTROLLER_LOGGER.trace("Executing two-phase");

        configureDomainUUID(operation);

        MultiphaseOverallContext overallContext = new MultiphaseOverallContext(localHostControllerInfo);

        // Get a copy of the headers for use on the servers so they don't get disrupted by any handlers
        // Also get a copy of the rollout plan. Remove it from the headers as no one needs it but us
        final ModelNode operationHeaders = operation.get(OPERATION_HEADERS);
        final ModelNode rolloutPlan = operationHeaders.has(ROLLOUT_PLAN)
                ? operation.get(OPERATION_HEADERS).remove(ROLLOUT_PLAN) : new ModelNode();

        // Create the op we'll ask the HCs to execute
        final ModelNode slaveOp = operation.clone();
        slaveOp.get(OPERATION_HEADERS, EXECUTE_FOR_COORDINATOR).set(true);
        slaveOp.protect();

        HostControllerExecutionSupport localHCES = null;

        // If necessary, execute locally first. This gets all of the Stage.MODEL, Stage.RUNTIME, Stage.VERIFY
        // steps registered. A failure in those will prevent the rest of the steps below executing
        String localHostName = localHostControllerInfo.getLocalHostName();
        if (routing.isLocalCallNeeded(localHostName)) {
            localHCES = localSlaveHandler.addSteps(context, slaveOp.clone(), overallContext.getLocalContext());
        }

        // Add a step that on the way out fixes up the result/failure description. On the way in it does nothing.
        // We set the 'addFirst' param to 'true' so this is placed *before* any steps localSlaveHandler just added
        context.addStep(new DomainFinalResultHandler(overallContext, localHCES), OperationContext.Stage.MODEL, true);

        if (localHostControllerInfo.isMasterDomainController()) {

            // Add steps to invoke on the HC for each relevant slave
            Set<String> remoteHosts = new HashSet<String>(routing.getHosts());
            boolean global = remoteHosts.size() == 0;
            remoteHosts.remove(localHostName);

            if (remoteHosts.size() > 0 || global) {

                if (routing.isMultiphase()) {
                    // Lock the controller to ensure there are no topology changes mid-op.
                    // This assumes registering/unregistering a remote proxy will involve an op and hence will block
                    //
                    // Notes non-multiphase case
                    // If the routing is non-multiphase we do not acquire the write lock here:
                    // - We don't worry about serverProxies, since there won't any results affecting the servers managed by this host.
                    // - The worst case here is if, in the middle of the operation, the target host is removed. In this case and if
                    // a host is removed (user concurrently shutdown it or its process crashes), this operation could fail, however,
                    // it is considered an expected failure.
                    context.acquireControllerLock();
                }

                if (global) {
                    remoteHosts.addAll(hostProxies.keySet());
                }

                Map<String, ProxyController> remoteProxies = new HashMap<String, ProxyController>();
                for (String host : remoteHosts) {
                    ProxyController proxy = hostProxies.get(host);
                    if (proxy != null) {
                        remoteProxies.put(host, proxy);
                    } else if (!global) {
                        throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.invalidOperationTargetHost(host);
                    }
                }

                context.addStep(slaveOp.clone(), new DomainSlaveHandler(remoteProxies, overallContext), OperationContext.Stage.DOMAIN);
            }
        }

        // Finally, the step to formulate and execute the 2nd phase rollout plan
        context.addStep(new DomainRolloutStepHandler(hostProxies, serverProxies, overallContext, rolloutPlan, operationHeaders, getExecutorService()), OperationContext.Stage.DOMAIN);
    }
 
Example 15
Source File: MBeanInfoFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private OpenMBeanParameterInfo[] getParameterInfos(ModelNode opNode) {
    if (!opNode.hasDefined(REQUEST_PROPERTIES)) {
        return EMPTY_PARAMETERS;
    }
    List<Property> propertyList = opNode.get(REQUEST_PROPERTIES).asPropertyList();
    List<OpenMBeanParameterInfo> params = new ArrayList<OpenMBeanParameterInfo>(propertyList.size());

    for (Property prop : propertyList) {
        ModelNode value = prop.getValue();
        String paramName = NameConverter.convertToCamelCase(prop.getName());

        Map<String, Object> descriptions = new HashMap<String, Object>(4);

        boolean expressionsAllowed = prop.getValue().hasDefined(EXPRESSIONS_ALLOWED) && prop.getValue().get(EXPRESSIONS_ALLOWED).asBoolean();
        descriptions.put(DESC_EXPRESSIONS_ALLOWED, String.valueOf(expressionsAllowed));

        if (!expressionsAllowed) {
            Object defaultValue = getIfExists(value, DEFAULT);
            descriptions.put(DEFAULT_VALUE_FIELD, defaultValue);
            if (value.has(ALLOWED)) {
                if (value.get(TYPE).asType()!=ModelType.LIST){
                    List<ModelNode> allowed = value.get(ALLOWED).asList();
                    descriptions.put(LEGAL_VALUES_FIELD, fromModelNodes(allowed));
                }
            } else {
                if (value.has(MIN)) {
                    Comparable minC = getIfExistsAsComparable(value, MIN);
                    if (minC instanceof Number) {
                        descriptions.put(MIN_VALUE_FIELD, minC);
                    }
                }
                if (value.has(MAX)) {
                    Comparable maxC = getIfExistsAsComparable(value, MAX);
                    if (maxC instanceof Number) {
                        descriptions.put(MAX_VALUE_FIELD, maxC);
                    }
                }
            }
        }


        params.add(
                new OpenMBeanParameterInfoSupport(
                        paramName,
                        getDescription(prop.getValue()),
                        converters.convertToMBeanType(value),
                        new ImmutableDescriptor(descriptions)));

    }
    return params.toArray(new OpenMBeanParameterInfo[params.size()]);
}
 
Example 16
Source File: AbstractDistributionCommand.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public CommandResult execute(CLICommandInvocation commandInvocation) throws CommandException, InterruptedException {
    if (host != null && !commandInvocation.getCommandContext().isDomainMode()) {
        throw new CommandException("The --host option is not available in the current context. "
                + "Connection to the controller might be unavailable or not running in domain mode.");
    } else if (host == null && commandInvocation.getCommandContext().isDomainMode()) {
        throw new CommandException("The --host option must be used in domain mode.");
    }
    final PatchOperationTarget target = createPatchOperationTarget(commandInvocation.getCommandContext());
    final PatchOperationBuilder builder = createPatchOperationBuilder(commandInvocation.getCommandContext());
    final ModelNode response;
    try {
        response = builder.execute(target);
    } catch (Exception e) {
        throw new CommandException(action + " failed", e);
    }
    if (!Util.isSuccess(response)) {
        final ModelNode fd = response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION);
        if (!fd.isDefined()) {
            throw new CommandException("Failed to apply patch: " + response.asString());
        }
        if (fd.has(Constants.CONFLICTS)) {
            final StringBuilder buf = new StringBuilder();
            buf.append(fd.get(Constants.MESSAGE).asString()).append(": ");
            final ModelNode conflicts = fd.get(Constants.CONFLICTS);
            String title = "";
            if (conflicts.has(Constants.BUNDLES)) {
                formatConflictsList(buf, conflicts, "", Constants.BUNDLES);
                title = ", ";
            }
            if (conflicts.has(Constants.MODULES)) {
                formatConflictsList(buf, conflicts, title, Constants.MODULES);
                title = ", ";
            }
            if (conflicts.has(Constants.MISC)) {
                formatConflictsList(buf, conflicts, title, Constants.MISC);
            }
            buf.append(lineSeparator).append("Use the --override-all, --override=[] or --preserve=[] arguments in order to resolve the conflict.");
            throw new CommandException(buf.toString());
        } else {
            throw new CommandException(Util.getFailureDescription(response));
        }
    }
    handleResponse(commandInvocation.getCommandContext(), response);
    return CommandResult.SUCCESS;
}
 
Example 17
Source File: ValueTypeCompleter.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected boolean isBytes(ModelNode propType) {
    if (propType.has(Util.TYPE)) {
        return typeEquals(propType.get(Util.TYPE), ModelType.BYTES);
    }
    return false;
}
 
Example 18
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 19
Source File: ObjectTypeAttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void addValueTypeDescription(final ModelNode node, final String prefix, final ResourceBundle bundle,
                                       boolean forOperation,
                                       final ResourceDescriptionResolver resolver,
                                       final Locale locale) {
    for (AttributeDefinition valueType : valueTypes) {
        if (forOperation && valueType.isResourceOnly()) {
            continue; //WFCORE-597
        }
        // get the value type description of the attribute
        final ModelNode valueTypeDesc = valueType.getNoTextDescription(false);
        if(valueTypeDesc.has(ModelDescriptionConstants.ATTRIBUTE_GROUP)) {
            valueTypeDesc.remove(ModelDescriptionConstants.ATTRIBUTE_GROUP);
        }
        final String p;
        boolean prefixUnusable = prefix == null || prefix.isEmpty() ;
        boolean suffixUnusable = suffix == null || suffix.isEmpty() ;

        if (prefixUnusable && !suffixUnusable) {
            p = suffix;
        } else if (!prefixUnusable && suffixUnusable) {
            p = prefix;
        } else {
            p = String.format("%s.%s", prefix, suffix);
        }

        // get the text description of the attribute
        if (resolver != null) {
            final String key = String.format("%s.%s", p, valueType.getName());
            valueTypeDesc.get(ModelDescriptionConstants.DESCRIPTION).set(resolver.getResourceAttributeDescription(key, locale, bundle));
        } else {
            valueTypeDesc.get(ModelDescriptionConstants.DESCRIPTION).set(valueType.getAttributeTextDescription(bundle, p));
        }

        // set it as one of our value types, and return the value
        final ModelNode childType = node.get(ModelDescriptionConstants.VALUE_TYPE, valueType.getName()).set(valueTypeDesc);
        // if it is of type OBJECT itself (add its nested descriptions)
        // seeing that OBJECT represents a grouping, use prefix+"."+suffix for naming the entries
        if (valueType instanceof ObjectTypeAttributeDefinition) {
            ObjectTypeAttributeDefinition.class.cast(valueType).addValueTypeDescription(childType, p, bundle, forOperation, resolver, locale);
        }
        // if it is of type LIST, and its value type
        // seeing that LIST represents a grouping, use prefix+"."+suffix for naming the entries
        if (valueType instanceof SimpleListAttributeDefinition) {
            SimpleListAttributeDefinition.class.cast(valueType).addValueTypeDescription(childType, p, bundle);
        } else if (valueType instanceof MapAttributeDefinition) {
            MapAttributeDefinition.class.cast(valueType).addValueTypeDescription(childType, bundle);
        } else if (valueType instanceof PrimitiveListAttributeDefinition) {
            PrimitiveListAttributeDefinition.class.cast(valueType).addValueTypeDescription(childType, bundle);
        } else if (valueType instanceof ObjectListAttributeDefinition) {
            ObjectListAttributeDefinition.class.cast(valueType).addValueTypeDescription(childType, p, bundle, false, resolver, locale);
        }
    }
}
 
Example 20
Source File: AttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Finds a value in the given {@code model} whose key matches this attribute's {@link #getName() name},
 * uses the given {@code resolver} to {@link ExpressionResolver#resolveExpressions(org.jboss.dmr.ModelNode)} resolve}
 * it and validates it using this attribute's {@link #getValidator() validator}. If the value is
 * undefined and a {@link #getDefaultValue() default value} is available, the default value is used.
 *
 * @param resolver the expression resolver
 * @param model model node of type {@link ModelType#OBJECT}, typically representing a model resource
 *
 * @return the resolved value, possibly the default value if the model does not have a defined value matching
 *              this attribute's name
 * @throws OperationFailedException if the value is not valid
 */
public ModelNode resolveModelAttribute(final ExpressionResolver resolver, final ModelNode model) throws OperationFailedException {
    final ModelNode node = new ModelNode();
    if(model.has(name)) {
        node.set(model.get(name));
    }
    return resolveValue(resolver, node);
}