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

The following examples show how to use org.jboss.dmr.ModelNode#setEmptyList() . 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: ThreadMXBeanFindMonitorDeadlockedThreadsHandler.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 {

    try {
        long[] ids = ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads();
        final ModelNode result = context.getResult();
        if (ids != null) {
            result.setEmptyList();
            for (long id : ids) {
                result.add(id);
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 2
Source File: ControlledCommandActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected boolean isAddressValid(CommandContext ctx,
        OperationRequestAddress requiredAddress) {
    final ModelNode request = new ModelNode();
    final ModelNode address = request.get(Util.ADDRESS);
    address.setEmptyList();
    request.get(Util.OPERATION).set(Util.VALIDATE_ADDRESS);
    final ModelNode addressValue = request.get(Util.VALUE);
    for (OperationRequestAddress.Node node : requiredAddress) {
        addressValue.add(node.getType(), node.getName());
    }
    final ModelNode response;
    try {
        response = ctx.getModelControllerClient().execute(request);
    } catch (IOException e) {
        return false;
    }
    final ModelNode result = response.get(Util.RESULT);
    if (!result.isDefined()) {
        return false;
    }
    final ModelNode valid = result.get(Util.VALID);
    if (!valid.isDefined()) {
        return false;
    }
    return valid.asBoolean();
}
 
Example 3
Source File: ManagementReadsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testServerReadResourceDescription() throws IOException {

    DomainClient domainClient = domainMasterLifecycleUtil.getDomainClient();
    ModelNode request = new ModelNode();
    request.get(OP).set("read-resource-description");
    ModelNode address = request.get(OP_ADDR);
    address.add(HOST, "master");
    address.add(SERVER, "main-one");
    request.get(RECURSIVE).set(true);
    request.get(OPERATIONS).set(true);

    ModelNode response = domainClient.execute(request);
    validateResponse(response);
    validateServerLifecycleOps(response, true);
    // TODO make some more assertions about result content

    address.setEmptyList();
    address.add(HOST, "slave");
    address.add(SERVER, "main-three");
    response = domainClient.execute(request);
    validateResponse(response);
    // TODO make some more assertions about result content
}
 
Example 4
Source File: BaseOperationCommand.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected boolean isAddressValid(CommandContext ctx) {
    final ModelNode request = new ModelNode();
    final ModelNode address = request.get(Util.ADDRESS);
    address.setEmptyList();
    request.get(Util.OPERATION).set(Util.VALIDATE_ADDRESS);
    final ModelNode addressValue = request.get(Util.VALUE);
    for(OperationRequestAddress.Node node : requiredAddress) {
        addressValue.add(node.getType(), node.getName());
    }
    final ModelNode response;
    try {
        response = ctx.getModelControllerClient().execute(request);
    } catch (IOException e) {
        return false;
    }
    final ModelNode result = response.get(Util.RESULT);
    if(!result.isDefined()) {
        return false;
    }
    final ModelNode valid = result.get(Util.VALID);
    if(!valid.isDefined()) {
        return false;
    }
    return valid.asBoolean();
}
 
Example 5
Source File: ThreadMXBeanFindDeadlockedThreadsHandler.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 {

    try {
        long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
        final ModelNode result = context.getResult();
        if (ids != null) {
            result.setEmptyList();
            for (long id : ids) {
                result.add(id);
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 6
Source File: ModelControllerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private OperationResponseImpl(ModelNode simpleResponse, Map<String, StreamEntry> inputStreams) {
    this.simpleResponse = simpleResponse;
    this.inputStreams = inputStreams;
    // TODO doing this here isn't so nice
    ModelNode header = simpleResponse.get(RESPONSE_HEADERS, ATTACHED_STREAMS);
    header.setEmptyList();
    for (StreamEntry entry : inputStreams.values()) {
        ModelNode streamNode = new ModelNode();
        streamNode.get(UUID).set(entry.getUUID());
        streamNode.get(MIME_TYPE).set(entry.getMimeType());
        header.add(streamNode);
    }
}
 
Example 7
Source File: SecurityDomainJBossASClient.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Given the name of an existing security domain that uses the SecureIdentity authentication method,
 * this updates that domain with the new credentials. Use this to change credentials if you don't
 * want to use expressions as the username or password entry (in some cases you can't, see the JIRA
 * https://issues.jboss.org/browse/AS7-5177 for more info).
 *
 * @param securityDomainName the name of the security domain whose credentials are to change
 * @param username the new username to be associated with the security domain
 * @param password the new value of the password to store in the configuration
 *                 (e.g. the obfuscated password itself)
 *
 * @throws Exception if failed to update security domain
 */
public void updateSecureIdentitySecurityDomainCredentials(String securityDomainName, String username,
        String password) throws Exception {

    Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName,
            AUTHENTICATION, CLASSIC);

    ModelNode loginModule = new ModelNode();
    loginModule.get(CODE).set("SecureIdentity");
    loginModule.get(FLAG).set("required");
    ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
    moduleOptions.setEmptyList();
    addPossibleExpression(moduleOptions, USERNAME, username);
    addPossibleExpression(moduleOptions, PASSWORD, password);

    // login modules attribute must be a list - we only have one item in it, the loginModule
    ModelNode loginModuleList = new ModelNode();
    loginModuleList.setEmptyList();
    loginModuleList.add(loginModule);

    final ModelNode op = createRequest(WRITE_ATTRIBUTE, addr);
    op.get(NAME).set(LOGIN_MODULES);
    op.get(VALUE).set(loginModuleList);

    ModelNode results = execute(op);
    if (!isSuccess(results)) {
        throw new FailureException(results, "Failed to update credentials for security domain ["
                + securityDomainName + "]");
    }

    return;
}
 
Example 8
Source File: SecurityDomainJBossASClient.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new security domain using the database server authentication method.
 * This is used when you want to directly authenticate against a db entry.
 * This is for AS 7.2+ (e.g. EAP 6.1) and works around https://issues.jboss.org/browse/AS7-6527
 *
 * @param securityDomainName the name of the new security domain
 * @param dsJndiName the jndi name for the datasource to query against
 * @param principalsQuery the SQL query for selecting password info for a principal
 * @param rolesQuery the SQL query for selecting role info for a principal
 * @param hashAlgorithm if null defaults to "MD5"
 * @param hashEncoding if null defaults to "base64"
 * @throws Exception if failed to create security domain
 */
public void createNewDatabaseServerSecurityDomain72(String securityDomainName, String dsJndiName,
        String principalsQuery, String rolesQuery, String hashAlgorithm,
        String hashEncoding) throws Exception {

    Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
    ModelNode addTopNode = createRequest(ADD, addr);
    addTopNode.get(CACHE_TYPE).set("default");

    Address authAddr = addr.clone().add(AUTHENTICATION, CLASSIC);
    ModelNode addAuthNode = createRequest(ADD, authAddr);

    // Create the login module in a separate step
    Address loginAddr = authAddr.clone().add("login-module", "Database"); // name = code
    ModelNode loginModule = createRequest(ADD, loginAddr); //addAuthNode.get(LOGIN_MODULES);
    loginModule.get(CODE).set("Database");
    loginModule.get(FLAG).set("required");
    ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
    moduleOptions.setEmptyList();
    moduleOptions.add(DS_JNDI_NAME, dsJndiName);
    moduleOptions.add(PRINCIPALS_QUERY, principalsQuery);
    moduleOptions.add(ROLES_QUERY, rolesQuery);
    moduleOptions.add(HASH_ALGORITHM, (null == hashAlgorithm ? "MD5" : hashAlgorithm));
    moduleOptions.add(HASH_ENCODING, (null == hashEncoding ? "base64" : hashEncoding));

    ModelNode batch = createBatchRequest(addTopNode, addAuthNode, loginModule);
    ModelNode results = execute(batch);
    if (!isSuccess(results)) {
        throw new FailureException(results, "Failed to create security domain [" + securityDomainName + "]");
    }

    return;
}
 
Example 9
Source File: ExpressionResolverImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Examine the given model node, resolving any expressions found within, including within child nodes.
 *
 * @param node the node
 * @return a node with all expressions resolved
 * @throws OperationFailedException if an expression cannot be resolved
 */
private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {
    if (!node.isDefined()) {
        return node;
    }

    ModelType type = node.getType();
    ModelNode resolved;
    if (type == ModelType.EXPRESSION) {
        resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);
    } else if (type == ModelType.OBJECT) {
        resolved = node.clone();
        for (Property prop : resolved.asPropertyList()) {
            resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));
        }
    } else if (type == ModelType.LIST) {
        resolved = node.clone();
        ModelNode list = new ModelNode();
        list.setEmptyList();
        for (ModelNode current : resolved.asList()) {
            list.add(resolveExpressionsRecursively(current));
        }
        resolved = list;
    } else if (type == ModelType.PROPERTY) {
        resolved = node.clone();
        resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));
    } else {
        resolved = node;
    }

    return resolved;
}
 
Example 10
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void updateModel(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
    final Resource resource = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS);
    final ModelNode handlerName = operation.get(HANDLER_NAME.getName());
    // Get the current handlers, add the handler and set the model value
    final ModelNode handlers = model.get(SUBHANDLERS.getName()).clone();
    if (!handlers.isDefined()) {
        handlers.setEmptyList();
    }
    handlers.add(handlerName);
    SUBHANDLERS.getValidator().validateParameter(SUBHANDLERS.getName(), handlers);
    model.get(SUBHANDLERS.getName()).add(handlerName);
    HANDLER.addCapabilityRequirements(context, resource, handlerName);
}
 
Example 11
Source File: ReadOperationNamesHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
    if (registry == null) {
        throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.noSuchResourceType(context.getCurrentAddress()));
    }
    final Map<String, OperationEntry> operations = registry.getOperationDescriptions(PathAddress.EMPTY_ADDRESS, true);

    final boolean accessControl = ACCESS_CONTROL.resolveModelAttribute(context, operation).asBoolean();

    final ModelNode result = new ModelNode();
    if (operations.size() > 0) {
        final PathAddress address = context.getCurrentAddress();
        for (final Map.Entry<String, OperationEntry> entry : operations.entrySet()) {
            if (isVisible(entry.getValue(), context)) {
                boolean add = true;
                if (accessControl) {
                    ModelNode operationToCheck = Util.createOperation(entry.getKey(), address);
                    operationToCheck.get(OPERATION_HEADERS).set(operation.get(OPERATION_HEADERS));
                    AuthorizationResult authorizationResult = context.authorizeOperation(operationToCheck);
                    add = authorizationResult.getDecision() == Decision.PERMIT;
                }

                if (add) {
                    result.add(entry.getKey());
                } else {
                    context.getResponseHeaders().get(ModelDescriptionConstants.ACCESS_CONTROL, FILTERED_OPERATIONS).add(entry.getKey());
                }
            }
        }
    } else {
        result.setEmptyList();
    }
    context.getResult().set(result);
}
 
Example 12
Source File: ThreadMXBeanThreadInfosHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    try {
        final long[] ids = getIds(operation);
        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] infos;
        if (operation.hasDefined(PlatformMBeanConstants.LOCKED_MONITORS)) {
            lockedValidator.validate(operation);
            infos = mbean.getThreadInfo(ids,
                    operation.require(PlatformMBeanConstants.LOCKED_MONITORS).asBoolean(),
                    operation.require(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS).asBoolean());
        } else if (operation.hasDefined(PlatformMBeanConstants.MAX_DEPTH)) {
            depthValidator.validate(operation);
            infos = mbean.getThreadInfo(ids, operation.require(PlatformMBeanConstants.MAX_DEPTH).asInt());
        } else {
            infos = mbean.getThreadInfo(ids);
        }

        final ModelNode result = context.getResult();
        if (infos != null) {
            result.setEmptyList();
            for (ThreadInfo info : infos) {
                if (info != null) {
                    result.add(PlatformMBeanUtil.getDetypedThreadInfo(info, mbean.isThreadCpuTimeSupported()));
                } else {
                    // Add an undefined placeholder
                    result.add();
                }
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 13
Source File: RuntimeMXBeanAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
static void storeResult(final String name, final ModelNode store) {

        if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) {
            store.set(ManagementFactory.RUNTIME_MXBEAN_NAME);
        } else if (ModelDescriptionConstants.NAME.equals(name)) {
           String runtimeName;
           try {
              runtimeName = ManagementFactory.getRuntimeMXBean().getName();
           } catch (ArrayIndexOutOfBoundsException e) {
              // Workaround for OSX issue
              String localAddr;
              try {
                 localAddr = InetAddress.getByName(null).toString();
              } catch (UnknownHostException uhe) {
                 localAddr = "localhost";
              }
              runtimeName = new Random().nextInt() + "@" + localAddr;
           }
           store.set(runtimeName);
        } else if (PlatformMBeanConstants.VM_NAME.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getVmName());
        } else if (PlatformMBeanConstants.VM_VENDOR.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getVmVendor());
        } else if (PlatformMBeanConstants.VM_VERSION.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getVmVersion());
        } else if (PlatformMBeanConstants.SPEC_NAME.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getSpecName());
        } else if (PlatformMBeanConstants.SPEC_VENDOR.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getSpecVendor());
        } else if (PlatformMBeanConstants.SPEC_VERSION.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getSpecVersion());
        } else if (PlatformMBeanConstants.MANAGEMENT_SPEC_VERSION.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getManagementSpecVersion());
        } else if (PlatformMBeanConstants.CLASS_PATH.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getClassPath());
        } else if (PlatformMBeanConstants.LIBRARY_PATH.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getLibraryPath());
        } else if (PlatformMBeanConstants.BOOT_CLASS_PATH_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().isBootClassPathSupported());
        } else if (PlatformMBeanConstants.BOOT_CLASS_PATH.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getBootClassPath());
        } else if (PlatformMBeanConstants.INPUT_ARGUMENTS.equals(name)) {
            store.setEmptyList();
            for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
                store.add(arg);
            }
        } else if (PlatformMBeanConstants.UPTIME.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getUptime());
        } else if (PlatformMBeanConstants.START_TIME.equals(name)) {
            store.set(ManagementFactory.getRuntimeMXBean().getStartTime());
        } else if (PlatformMBeanConstants.SYSTEM_PROPERTIES.equals(name)) {
            store.setEmptyObject();
            final TreeMap<String, String> sorted = new TreeMap<>(ManagementFactory.getRuntimeMXBean().getSystemProperties());
            for (Map.Entry<String, String> prop : sorted.entrySet()) {
                final ModelNode propNode = store.get(prop.getKey());
                if (prop.getValue() != null) {
                    propNode.set(prop.getValue());
                }
            }
        } else if (RuntimeResourceDefinition.RUNTIME_READ_ATTRIBUTES.contains(name)
                || RuntimeResourceDefinition.RUNTIME_METRICS.contains(name)) {
            // Bug
            throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name);
        }

    }
 
Example 14
Source File: DomainXml_Legacy.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void parseSocketBindingGroup_1_0(final XMLExtendedStreamReader reader, final Set<String> interfaces, final ModelNode address,
                                         final List<ModelNode> updates) throws XMLStreamException {
    // unique socket-binding names
    final Set<String> uniqueBindingNames = new HashSet<String>();

    // Handle attributes
    final String[] attrValues = requireAttributes(reader, Attribute.NAME.getLocalName(), Attribute.DEFAULT_INTERFACE.getLocalName());
    final String socketBindingGroupName = attrValues[0];
    final String defaultInterface = attrValues[1];

    final ModelNode groupAddress = new ModelNode().set(address);
    groupAddress.add(SOCKET_BINDING_GROUP, socketBindingGroupName);

    final ModelNode bindingGroupUpdate = new ModelNode();
    bindingGroupUpdate.get(OP_ADDR).set(groupAddress);
    bindingGroupUpdate.get(OP).set(ADD);

    SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.parseAndSetParameter(defaultInterface, bindingGroupUpdate, reader);
    if (bindingGroupUpdate.get(SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.getName()).getType() != ModelType.EXPRESSION
            && !interfaces.contains(defaultInterface)) {
        throw ControllerLogger.ROOT_LOGGER.unknownInterface(defaultInterface, Attribute.DEFAULT_INTERFACE.getLocalName(), Element.INTERFACES.getLocalName(), reader.getLocation());
    }

    final ModelNode includes = bindingGroupUpdate.get(INCLUDES);
    includes.setEmptyList();
    updates.add(bindingGroupUpdate);

    // Handle elements
    while (reader.nextTag() != END_ELEMENT) {
        requireNamespace(reader, namespace);
        final Element element = Element.forName(reader.getLocalName());
        switch (element) {
            case INCLUDE: {
                ROOT_LOGGER.warnIgnoringSocketBindingGroupInclude(reader.getLocation());

                /* This will be reintroduced for 7.2.0, leave commented out
                 final String includedGroup = readStringAttributeElement(reader, Attribute.SOCKET_BINDING_GROUP.getLocalName());
                 if (!includedGroups.add(includedGroup)) {
                 throw MESSAGES.alreadyDeclared(Attribute.SOCKET_BINDING_GROUP.getLocalName(), includedGroup, reader.getLocation());
                 }
                 AbstractSocketBindingGroupResourceDefinition.INCLUDES.parseAndAddParameterElement(includedGroup, bindingGroupUpdate, reader.getLocation());
                 */
                break;
            }
            case SOCKET_BINDING: {
                final String bindingName = parseSocketBinding(reader, interfaces, groupAddress, updates);
                if (!uniqueBindingNames.add(bindingName)) {
                    throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation());
                }
                break;
            }
            default:
                throw unexpectedElement(reader);
        }
    }
}
 
Example 15
Source File: GarbageCollectorMXBeanAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected void executeReadAttribute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final String gcName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
    final String name = operation.require(ModelDescriptionConstants.NAME).asString();

    GarbageCollectorMXBean gcMBean = null;

    for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
        if (gcName.equals(escapeMBeanName(mbean.getName()))) {
            gcMBean = mbean;
        }
    }

    if (gcMBean == null) {
        throw PlatformMBeanLogger.ROOT_LOGGER.unknownGarbageCollector(gcName);
    }

    if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) {
        final String objName = PlatformMBeanUtil.getObjectNameStringWithNameKey(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE, gcName);
        context.getResult().set(objName);
    } else if (ModelDescriptionConstants.NAME.equals(name)) {
        context.getResult().set(escapeMBeanName(gcMBean.getName()));
    } else if (PlatformMBeanConstants.VALID.getName().equals(name)) {
        context.getResult().set(gcMBean.isValid());
    } else if (PlatformMBeanConstants.MEMORY_POOL_NAMES.equals(name)) {
        final ModelNode result = context.getResult();
        result.setEmptyList();
        for (String pool : gcMBean.getMemoryPoolNames()) {
            result.add(escapeMBeanName(pool));
        }
    } else if (PlatformMBeanConstants.COLLECTION_COUNT.equals(name)) {
        context.getResult().set(gcMBean.getCollectionCount());
    } else if (PlatformMBeanConstants.COLLECTION_TIME.equals(name)) {
        context.getResult().set(gcMBean.getCollectionTime());
    } else if (GarbageCollectorResourceDefinition.GARBAGE_COLLECTOR_READ_ATTRIBUTES.contains(name)
            || GarbageCollectorResourceDefinition.GARBAGE_COLLECTOR_METRICS.contains(name)) {
        // Bug
        throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name);
    } else {
        // Shouldn't happen; the global handler should reject
        throw unknownAttribute(operation);
    }

}
 
Example 16
Source File: ReadChildrenNamesHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final PathAddress address = context.getCurrentAddress();
    final String childType = CHILD_TYPE.resolveModelAttribute(context, operation).asString();
    final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false);
    ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
    Map<String, Set<String>> childAddresses = GlobalOperationHandlers.getChildAddresses(context, address, registry, resource, childType);
    Set<String> childNames = childAddresses.get(childType);
    if (childNames == null) {
        throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.unknownChildType(childType));
    }
    final boolean singletons = INCLUDE_SINGLETONS.resolveModelAttribute(context, operation).asBoolean(false);
    if (singletons && isSingletonResource(registry, childType)) {
        Set<PathElement> childTypes = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);
        for (PathElement child : childTypes) {
            if (childType.equals(child.getKey())) {
                childNames.add(child.getValue());
            }
        }
    }
    // Sort the result
    childNames = new TreeSet<String>(childNames);
    ModelNode result = context.getResult();
    result.setEmptyList();
    PathAddress childAddress = address.append(PathElement.pathElement(childType));
    ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, childAddress);
    op.get(OPERATION_HEADERS).set(operation.get(OPERATION_HEADERS));
    ModelNode opAddr = op.get(OP_ADDR);
    ModelNode childProperty = opAddr.require(address.size());
    Set<Action.ActionEffect> actionEffects = EnumSet.of(Action.ActionEffect.ADDRESS);
    FilteredData fd = null;
    for (String childName : childNames) {
        childProperty.set(childType, new ModelNode(childName));
        if (context.authorize(op, actionEffects).getDecision() == AuthorizationResult.Decision.PERMIT) {
            result.add(childName);
        } else {
            if (fd == null) {
                fd = new FilteredData(address);
            }
            fd.addAccessRestrictedResource(childAddress);
        }
    }

    if (fd != null) {
        context.getResponseHeaders().get(ACCESS_CONTROL).set(fd.toModelNode());
    }
}
 
Example 17
Source File: ThreadMXBeanAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
static void storeResult(final String name, final ModelNode store) {

        if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) {
            store.set(ManagementFactory.THREAD_MXBEAN_NAME);
        } else if (PlatformMBeanConstants.THREAD_COUNT.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getThreadCount());
        } else if (PlatformMBeanConstants.PEAK_THREAD_COUNT.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getPeakThreadCount());
        } else if (PlatformMBeanConstants.TOTAL_STARTED_THREAD_COUNT.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getTotalStartedThreadCount());
        } else if (PlatformMBeanConstants.DAEMON_THREAD_COUNT.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getDaemonThreadCount());
        } else if (PlatformMBeanConstants.ALL_THREAD_IDS.equals(name)) {
            store.setEmptyList();
            for (Long id : ManagementFactory.getThreadMXBean().getAllThreadIds()) {
                store.add(id);
            }
        } else if (PlatformMBeanConstants.THREAD_CONTENTION_MONITORING_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isThreadContentionMonitoringSupported());
        } else if (PlatformMBeanConstants.THREAD_CONTENTION_MONITORING_ENABLED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isThreadContentionMonitoringEnabled());
        } else if (PlatformMBeanConstants.CURRENT_THREAD_CPU_TIME.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime());
        } else if (PlatformMBeanConstants.CURRENT_THREAD_USER_TIME.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().getCurrentThreadUserTime());
        } else if (PlatformMBeanConstants.THREAD_CPU_TIME_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isThreadCpuTimeSupported());
        } else if (PlatformMBeanConstants.CURRENT_THREAD_CPU_TIME_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isCurrentThreadCpuTimeSupported());
        } else if (PlatformMBeanConstants.THREAD_CPU_TIME_ENABLED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isThreadCpuTimeEnabled());
        } else if (PlatformMBeanConstants.OBJECT_MONITOR_USAGE_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isObjectMonitorUsageSupported());
        } else if (PlatformMBeanConstants.SYNCHRONIZER_USAGE_SUPPORTED.equals(name)) {
            store.set(ManagementFactory.getThreadMXBean().isSynchronizerUsageSupported());
        } else if (ThreadResourceDefinition.THREADING_READ_ATTRIBUTES.contains(name)
                || ThreadResourceDefinition.THREADING_READ_WRITE_ATTRIBUTES.contains(name)
                || ThreadResourceDefinition.THREADING_METRICS.contains(name)) {
            // Bug
            throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name);
        }

    }
 
Example 18
Source File: AnalysisContext.java    From revapi with Apache License 2.0 4 votes vote down vote up
private ModelNode convertToNewStyle(ModelNode configuration) {
    if (configuration.getType() == ModelType.LIST) {
        Map<String, Set<String>> idsByExtension = new HashMap<>(4);
        for (ModelNode c : configuration.asList()) {

            if (c.hasDefined("id")) {
                String extension = c.get("extension").asString();
                String id = c.get("id").asString();

                boolean added = idsByExtension.computeIfAbsent(extension, x -> new HashSet<>(2)).add(id);
                if (!added) {
                    throw new IllegalArgumentException(
                            "A configuration cannot contain 2 extension configurations with the same id. " +
                                    "At least 2 extension configurations of extension '" + extension +
                                    "' have the id '" + id + "'.");
                }
            }
        }

        return configuration;
    }

    if (knownExtensionIds == null) {
        throw new IllegalArgumentException(
                "The analysis context builder wasn't supplied with the list of known extension ids," +
                        " so it only can process new-style configurations.");
    }

    ModelNode newStyleConfig = new ModelNode();
    newStyleConfig.setEmptyList();

    extensionScan:
    for (String extensionId : knownExtensionIds) {
        String[] explodedId = extensionId.split("\\.");

        ModelNode extConfig = configuration;
        for (String segment : explodedId) {
            if (!extConfig.hasDefined(segment)) {
                continue extensionScan;
            } else {
                extConfig = extConfig.get(segment);
            }
        }

        ModelNode extNewStyle = new ModelNode();
        extNewStyle.get("extension").set(extensionId);
        extNewStyle.get("configuration").set(extConfig);

        newStyleConfig.add(extNewStyle);
    }

    return newStyleConfig;
}
 
Example 19
Source File: SecurityDomainJBossASClient.java    From hawkular-agent with Apache License 2.0 4 votes vote down vote up
private void createNewSecurityDomain72(String securityDomainName, LoginModuleRequest... loginModules)
        throws Exception {

    if (isSecurityDomain(securityDomainName)) {
        removeSecurityDomain(securityDomainName);
    }

    Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);

    ModelNode addTopNode = createRequest(ADD, addr);
    addTopNode.get(CACHE_TYPE).set("default");

    Address authAddr = addr.clone().add(AUTHENTICATION, CLASSIC);
    ModelNode addAuthNode = createRequest(ADD, authAddr);

    // We add each login module via its own :add request
    // Add the start we put the 2 "top nodes" so that it works with the varargs below
    ModelNode[] steps = new ModelNode[loginModules.length + 2];
    steps[0] = addTopNode;
    steps[1] = addAuthNode;

    for (int i = 0; i < loginModules.length; i++) {
        LoginModuleRequest moduleRequest = loginModules[i];
        Address loginAddr = authAddr.clone().add("login-module", moduleRequest.getLoginModuleFQCN());

        ModelNode loginModule = createRequest(ADD, loginAddr);
        loginModule.get(CODE).set(moduleRequest.getLoginModuleFQCN());
        loginModule.get(FLAG).set(moduleRequest.getFlagString());
        ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
        moduleOptions.setEmptyList();

        Map<String, String> moduleOptionProperties = moduleRequest.getModuleOptionProperties();
        if (null != moduleOptionProperties) {
            for (String key : moduleOptionProperties.keySet()) {
                String value = moduleOptionProperties.get(key);
                if (null != value) {
                    moduleOptions.add(key, value);
                }
            }
        }

        steps[i + 2] = loginModule;
    }

    ModelNode batch = createBatchRequest(steps);
    ModelNode results = execute(batch);
    if (!isSuccess(results)) {
        throw new FailureException(results, "Failed to create security domain [" + securityDomainName + "]");
    }

    return;
}
 
Example 20
Source File: BootErrorCollector.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public BootErrorCollector() {
    errors = new ModelNode();
    errors.setEmptyList();
    listBootErrorsHandler = new ListBootErrorsHandler(this);
}