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

The following examples show how to use org.jboss.dmr.ModelNode#asInt() . 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: ConnectorUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected static OptionMap getFullOptions(OperationContext context, ModelNode fullModel) throws OperationFailedException {
    OptionMap.Builder builder = OptionMap.builder();
    builder.set(Options.TCP_NODELAY, true);
    builder.set(Options.REUSE_ADDRESSES, true);

    builder.set(RemotingOptions.SASL_PROTOCOL, ConnectorCommon.SASL_PROTOCOL.resolveModelAttribute(context, fullModel).asString());
    ModelNode serverName = ConnectorCommon.SERVER_NAME.resolveModelAttribute(context, fullModel);
    if (serverName.isDefined()) {
        builder.set(RemotingOptions.SERVER_NAME, serverName.asString());
    }

    ModelNode properties = fullModel.get(PROPERTY);
    if (properties.isDefined() && properties.asInt() > 0) {
        addOptions(context, properties, builder);
    }
    if (fullModel.hasDefined(SECURITY)) {
        ModelNode security = fullModel.require(SECURITY);
        if (security.hasDefined(SASL)) {
            ModelNode sasl = security.require(SASL);
            addSasl(context, sasl, builder);
        }
    }
    return builder.getMap();
}
 
Example 2
Source File: ThreadPoolManagementUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static BoundedThreadPoolParameters parseBoundedThreadPoolParameters(final OperationContext context, final ModelNode operation, final ModelNode model, boolean blocking) throws OperationFailedException {
    ThreadPoolParametersImpl params = new ThreadPoolParametersImpl();
    parseBaseThreadPoolOperationParameters(context, operation, model, params);

    params.allowCoreTimeout = PoolAttributeDefinitions.ALLOW_CORE_TIMEOUT.resolveModelAttribute(context, model).asBoolean();
    if (!blocking) {
        ModelNode handoffEx = PoolAttributeDefinitions.HANDOFF_EXECUTOR.resolveModelAttribute(context, model);
        params.handoffExecutor = handoffEx.isDefined() ? handoffEx.asString() : null;
    }
    ModelNode coreTh = PoolAttributeDefinitions.CORE_THREADS.resolveModelAttribute(context, model);
    params.coreThreads = coreTh.isDefined() ? coreTh.asInt() : params.maxThreads;
    params.queueLength = PoolAttributeDefinitions.QUEUE_LENGTH.resolveModelAttribute(context, model).asInt();
    return params;
}
 
Example 3
Source File: BoundedQueueThreadPoolWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void applyOperation(final OperationContext context, ModelNode model, String attributeName,
                              ServiceController<?> service, boolean forRollback) throws OperationFailedException {

    final BoundedQueueThreadPoolService pool =  (BoundedQueueThreadPoolService) service.getService();

    if (PoolAttributeDefinitions.KEEPALIVE_TIME.getName().equals(attributeName)) {
        TimeUnit defaultUnit = pool.getKeepAliveUnit();
        final TimeSpec spec = getTimeSpec(context, model, defaultUnit);
        pool.setKeepAlive(spec);
    } else if(PoolAttributeDefinitions.MAX_THREADS.getName().equals(attributeName)) {
        pool.setMaxThreads(PoolAttributeDefinitions.MAX_THREADS.resolveModelAttribute(context, model).asInt());
    } else if(PoolAttributeDefinitions.CORE_THREADS.getName().equals(attributeName)) {
        int coreCount;
        ModelNode coreNode = PoolAttributeDefinitions.CORE_THREADS.resolveModelAttribute(context, model);
        if (coreNode.isDefined()) {
            coreCount = coreNode.asInt();
        } else {
            // Core is same as max
            coreCount = PoolAttributeDefinitions.MAX_THREADS.resolveModelAttribute(context, model).asInt();
        }
        pool.setCoreThreads(coreCount);
    } else if(PoolAttributeDefinitions.QUEUE_LENGTH.getName().equals(attributeName)) {
        if (forRollback) {
            context.revertReloadRequired();
        } else {
            context.reloadRequired();
        }
    } else if (PoolAttributeDefinitions.ALLOW_CORE_TIMEOUT.getName().equals(attributeName)) {
        pool.setAllowCoreTimeout(PoolAttributeDefinitions.ALLOW_CORE_TIMEOUT.resolveModelAttribute(context, model).asBoolean());
    } else if (!forRollback) {
        // Programming bug. Throw a RuntimeException, not OFE, as this is not a client error
        throw ThreadsLogger.ROOT_LOGGER.unsupportedBoundedQueueThreadPoolAttribute(attributeName);
    }
}
 
Example 4
Source File: IntRangeValidator.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
    super.validateParameter(parameterName, value);
    if (value.isDefined() && value.getType() != ModelType.EXPRESSION) {
        int val = value.asInt();
        if (val < min) {
            throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMinValue(val, parameterName, min));
        }
        else if (val > max) {
            throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMaxValue(val, parameterName, max));
        }
    }
}
 
Example 5
Source File: ConnectorUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static OptionMap getOptions(OperationContext context, ModelNode properties) throws OperationFailedException {
    if (properties.isDefined() && properties.asInt() > 0) {
        OptionMap.Builder builder = OptionMap.builder();
        addOptions(context, properties, builder);
        return builder.getMap();
    } else {
        return OptionMap.EMPTY;
    }
}
 
Example 6
Source File: OperationResponseProxy.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private OperationResponseProxy(final ModelNode responseNode, final ManagementChannelAssociation channelAssociation, final int batchId, final ModelNode streamHeader) {
    this.responseNode = responseNode;
    int size = streamHeader.asInt();
    proxiedStreams = new LinkedHashMap<String, StreamEntry>(size);
    for (int i = 0; i < size; i++) {
        ModelNode headerElement =  streamHeader.get(i);
        final String uuid = headerElement.require("uuid").asString();
        final String mimeType = headerElement.require("mime-type").asString();
        proxiedStreams.put(uuid, new ProxiedInputStream(uuid, mimeType, channelAssociation, batchId, i));
    }
}
 
Example 7
Source File: TransactionalProtocolClientImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static OperationResponse createOperationResponse(ModelNode simpleResponse, ManagementChannelAssociation channelAssociation, int operationId) {
    final ModelNode streamHeader =  simpleResponse.hasDefined(RESPONSE_HEADERS) && simpleResponse.get(RESPONSE_HEADERS).hasDefined(ATTACHED_STREAMS)
            ? simpleResponse.get(RESPONSE_HEADERS, ATTACHED_STREAMS)
            : null;
    if (streamHeader != null && streamHeader.asInt() > 0) {
        return OperationResponseProxy.create(simpleResponse, channelAssociation, operationId, streamHeader);
    } else {
        return OperationResponse.Factory.createSimple(simpleResponse);
    }
}
 
Example 8
Source File: OperationHeaders.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static OperationHeaders fromOperation(ModelNode operation) throws OperationFailedException {

        final EnumSet<OperationContextImpl.ContextFlag> contextFlags;
        Integer blockingTimeout = null;
        String warningLevel = null;
        String domainUUID = null;
        AccessMechanism accessMechanism = null;
        if (operation.hasDefined(OPERATION_HEADERS)) {
            final ModelNode headers = operation.get(OPERATION_HEADERS).clone();

            final boolean rollbackOnFailure = ROLLBACK.resolveModelAttribute(ExpressionResolver.REJECTING, headers).asBoolean();
            final boolean restartResourceServices = RESTART.resolveModelAttribute(ExpressionResolver.REJECTING, headers).asBoolean();
            contextFlags = rollbackOnFailure ? EnumSet.of(AbstractOperationContext.ContextFlag.ROLLBACK_ON_FAIL) : EnumSet.noneOf(OperationContextImpl.ContextFlag.class);
            if (restartResourceServices) {
                contextFlags.add(AbstractOperationContext.ContextFlag.ALLOW_RESOURCE_SERVICE_RESTART);
            }

            final ModelNode blockingTimeoutConfig = BLOCKING.resolveModelAttribute(ExpressionResolver.REJECTING, headers);
            if (blockingTimeoutConfig.isDefined()) {
                blockingTimeout = blockingTimeoutConfig.asInt();
                // Check the value is positive. We could use a ParameterValidator on the AttributeDefinition to do this but since
                // in the past we used this particular failure message, let's stick with it just to not change things.
                // Note that failure message compatibility has never been a requirement though, so we could change this.
                if (blockingTimeout < 1) {
                    throw ControllerLogger.MGMT_OP_LOGGER.invalidBlockingTimeout(blockingTimeout.longValue(), BLOCKING_TIMEOUT);
                }
            }

            warningLevel = headers.hasDefined(WARNING_LEVEL) ? headers.get(WARNING_LEVEL).asString() : null;
            domainUUID = headers.hasDefined(DOMAIN_UUID) ? headers.get(DOMAIN_UUID).asString() : null;
            accessMechanism = headers.hasDefined(ACCESS_MECHANISM) ? AccessMechanism.valueOf(headers.get(ACCESS_MECHANISM).asString()) : null;
        } else {
            contextFlags = EnumSet.of(AbstractOperationContext.ContextFlag.ROLLBACK_ON_FAIL);
        }

        return new OperationHeaders(contextFlags, blockingTimeout, warningLevel, domainUUID, accessMechanism);
    }
 
Example 9
Source File: JmxManagementInterface.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Object object(ModelNode node) {
    switch (node.getType()) {
        case BIG_DECIMAL:
            return node.asBigDecimal();
        case BIG_INTEGER:
            return node.asBigInteger();
        case BOOLEAN:
            return node.asBoolean();
        case BYTES:
            return node.asBytes();
        case DOUBLE:
            return node.asDouble();
        case EXPRESSION:
            return node.asExpression();
        case INT:
            return node.asInt();
        case LIST:
            return node.asList();
        case LONG:
            return node.asLong();
        case PROPERTY:
            return node.asProperty();
        case STRING:
            return node.asString();
        case UNDEFINED:
            return null;
        default:
            throw new UnsupportedOperationException("Can't convert '" + node.getType() + "' to object");
    }
}
 
Example 10
Source File: AdvancedModifiableKeyStoreDecorator.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
    super.validateParameter(parameterName, value);
    if (value.isDefined()) {
        int intValue = value.asInt();
        // check that the given value is a power of 2
        if ((intValue & (intValue - 1)) != 0) {
            throw ROOT_LOGGER.invalidKeySize(intValue);
        }
    }
}
 
Example 11
Source File: PolicyDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ModelNode correct(ModelNode newValue, ModelNode currentValue) {
    ModelNode result = newValue;
    if (newValue.getType() == ModelType.LIST && newValue.asInt() == 1) {
        // extract the single element
        result = newValue.get(0);
        if (result.has(NAME)) {
            result.remove(NAME);
        }
    }
    return result;
}
 
Example 12
Source File: DMRDriver.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
private static Object toObject(ModelNode value) throws ProtocolException {
    switch (value.getType()) {
        case BIG_DECIMAL:
            return value.asBigDecimal();
        case BIG_INTEGER:
            return value.asBigInteger();
        case BOOLEAN:
            return value.asBoolean();
        case BYTES:
            return value.asBytes();
        case DOUBLE:
            return value.asDouble();
        case INT:
            return value.asInt();
        case LONG:
            return value.asLong();
        case OBJECT:
            return value.asObject();
        case PROPERTY:
            return value.asProperty();
        case STRING:
            return value.asString();
        case UNDEFINED:
            return null;
        case LIST:
            return toObjectList(value.asList());
        default:
            throw new ProtocolException("cannot handle an attribute of type [" + value.getType() + "]");
    }
}
 
Example 13
Source File: TypeConverters.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
Object fromModelNode(final ModelNode node) {
    return node.asInt();
}
 
Example 14
Source File: WorkerAdd.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
    final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
    Resource resource = context.readResourceFromRoot(address.subAddress(0, address.size() - 1));
    ModelNode workers = Resource.Tools.readModel(resource).get(IOExtension.WORKER_PATH.getKey());
    int allWorkerCount = workers.asList().size();
    final String name = context.getCurrentAddressValue();
    final XnioWorker.Builder builder = Xnio.getInstance().createWorkerBuilder();

    final OptionMap.Builder optionMapBuilder = OptionMap.builder();

    for (OptionAttributeDefinition attr : WorkerResourceDefinition.ATTRIBUTES) {
        Option option = attr.getOption();
        ModelNode value = attr.resolveModelAttribute(context, model);
        if (!value.isDefined()) {
            continue;
        }
        if (attr.getType() == ModelType.INT) {
            optionMapBuilder.set((Option<Integer>) option, value.asInt());
        } else if (attr.getType() == ModelType.LONG) {
            optionMapBuilder.set(option, value.asLong());
        } else if (attr.getType() == ModelType.BOOLEAN) {
            optionMapBuilder.set(option, value.asBoolean());
        }
    }
    builder.populateFromOptions(optionMapBuilder.getMap());
    builder.setWorkerName(name);

    ModelNode ioThreadsModel = WORKER_IO_THREADS.resolveModelAttribute(context, model);
    ModelNode coreTaskThreadsModel = WORKER_TASK_CORE_THREADS.resolveModelAttribute(context, model);
    ModelNode maxTaskThreadsModel = WORKER_TASK_MAX_THREADS.resolveModelAttribute(context, model);
    int cpuCount = getCpuCount();
    int ioThreadsCalculated = getSuggestedIoThreadCount();
    int workerThreads = builder.getMaxWorkerPoolSize();
    int coreWorkerThreads = coreTaskThreadsModel.asInt();
    if (!ioThreadsModel.isDefined() && !maxTaskThreadsModel.isDefined()) {
        workerThreads = getWorkerThreads(name, allWorkerCount);
        builder.setWorkerIoThreads(ioThreadsCalculated);
        builder.setCoreWorkerPoolSize(coreWorkerThreads);
        builder.setMaxWorkerPoolSize(workerThreads);
        IOLogger.ROOT_LOGGER.printDefaults(name, ioThreadsCalculated, workerThreads, cpuCount);
    } else {
        if (!ioThreadsModel.isDefined()) {
            builder.setWorkerIoThreads(ioThreadsCalculated);
            IOLogger.ROOT_LOGGER.printDefaultsIoThreads(name, ioThreadsCalculated, cpuCount);
        }
        if (!maxTaskThreadsModel.isDefined()) {
            workerThreads = getWorkerThreads(name, allWorkerCount);
            builder.setCoreWorkerPoolSize(coreWorkerThreads);
            builder.setMaxWorkerPoolSize(workerThreads);
            IOLogger.ROOT_LOGGER.printDefaultsWorkerThreads(name, workerThreads, cpuCount);
        }
    }

    registerMax(context, name, workerThreads);

    final CapabilityServiceBuilder<?> capBuilder = context.getCapabilityServiceTarget().addCapability(IO_WORKER_RUNTIME_CAPABILITY);
    final Consumer<XnioWorker> workerConsumer = capBuilder.provides(IO_WORKER_RUNTIME_CAPABILITY);
    final Supplier<ExecutorService> executorSupplier = capBuilder.requiresCapability("org.wildfly.management.executor", ExecutorService.class);
    capBuilder.setInstance(new WorkerService(workerConsumer, executorSupplier, builder));
    capBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND);
    capBuilder.install();
}
 
Example 15
Source File: Client.java    From openshift-ping with Apache License 2.0 4 votes vote down vote up
public final List<Pod> getPods(String namespace, String labels) throws Exception {
    ModelNode root = getNode("pods", namespace, labels);
    List<Pod> pods = new ArrayList<Pod>();
    List<ModelNode> itemNodes = root.get("items").asList();
    for (ModelNode itemNode : itemNodes) {
        //ModelNode metadataNode = itemNode.get("metadata");
        //String podName = metadataNode.get("name").asString(); // eap-app-1-43wra
        //String podNamespace = metadataNode.get("namespace").asString(); // dward
        ModelNode specNode = itemNode.get("spec");
        //String serviceAccount = specNode.get("serviceAccount").asString(); // default
        //String host = specNode.get("host").asString(); // ce-openshift-rhel-minion-1.lab.eng.brq.redhat.com
        ModelNode statusNode = itemNode.get("status");
        ModelNode phaseNode = statusNode.get("phase");
        if (!phaseNode.isDefined() || !"Running".equals(phaseNode.asString())) {
            continue;
        }
        /* We don't want to filter on the following as that could result in MERGEs instead of JOINs.
        ModelNode conditionsNode = statusNode.get("conditions");
        if (!conditionsNode.isDefined()) {
            continue;
        }
        boolean ready = false;
        List<ModelNode> conditions = conditionsNode.asList();
        for (ModelNode condition : conditions) {
            ModelNode conditionTypeNode = condition.get("type");
            ModelNode conditionStatusNode = condition.get("status");
            if (conditionTypeNode.isDefined() && "Ready".equals(conditionTypeNode.asString()) &&
                    conditionStatusNode.isDefined() && "True".equals(conditionStatusNode.asString())) {
                ready = true;
                break;
            }
        }
        if (!ready) {
            continue;
        }
        */
        //String hostIP = statusNode.get("hostIP").asString(); // 10.34.75.250
        ModelNode podIPNode = statusNode.get("podIP");
        if (!podIPNode.isDefined()) {
            continue;
        }
        String podIP = podIPNode.asString(); // 10.1.0.169
        Pod pod = new Pod(podIP);
        ModelNode containersNode = specNode.get("containers");
        if (!containersNode.isDefined()) {
            continue;
        }
        List<ModelNode> containerNodes = containersNode.asList();
        for (ModelNode containerNode : containerNodes) {
            ModelNode portsNode = containerNode.get("ports");
            if (!portsNode.isDefined()) {
                continue;
            }
            //String containerName = containerNode.get("name").asString(); // eap-app
            Container container = new Container();
            List<ModelNode> portNodes = portsNode.asList();
            for (ModelNode portNode : portNodes) {
                ModelNode portNameNode = portNode.get("name");
                if (!portNameNode.isDefined()) {
                    continue;
                }
                String portName = portNameNode.asString(); // ping
                ModelNode containerPortNode = portNode.get("containerPort");
                if (!containerPortNode.isDefined()) {
                    continue;
                }
                int containerPort = containerPortNode.asInt(); // 8888
                Port port = new Port(portName, containerPort);
                container.addPort(port);
            }
            pod.addContainer(container);
        }
        pods.add(pod);
    }
    if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, String.format("getPods(%s, %s) = %s", namespace, labels, pods));
    }
    return pods;
}
 
Example 16
Source File: AccessConstraintUtilizationTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testConstraintUtilization() throws Exception {
    ModelControllerClient client = testSupport.getDomainMasterLifecycleUtil().getDomainClient();
    for (ExpectedDef expectedDef : EXPECTED_DEFS) {
        AccessConstraintKey acdKey = expectedDef.key;
        String constraint = ModelDescriptionConstants.SENSITIVE.equals(acdKey.getType())
                ? ModelDescriptionConstants.SENSITIVITY_CLASSIFICATION
                : ModelDescriptionConstants.APPLICATION_CLASSIFICATION;
        String acdType = acdKey.isCore() ? "core" : acdKey.getSubsystemName();
        String path = String.format(ADDR_FORMAT, acdKey.getType(), acdType, acdKey.getName());
        ModelNode op = createOpNode(path, READ_CHILDREN_RESOURCES_OPERATION);
        op.get(ModelDescriptionConstants.CHILD_TYPE).set(ModelDescriptionConstants.APPLIES_TO);
        System.out.println("Testing " + acdKey);
        ModelNode result = RbacUtil.executeOperation(client, op, Outcome.SUCCESS).get(ModelDescriptionConstants.RESULT);
        Assert.assertTrue(acdKey + "result is defined", result.isDefined());
        Assert.assertTrue(acdKey + "result has content", result.asInt() > 0);
        boolean foundResource = false;
        boolean foundAttr = false;
        boolean foundOps = false;
        for (Property prop : result.asPropertyList()) {
            ModelNode pathResult = prop.getValue();
            if (pathResult.get(ModelDescriptionConstants.ENTIRE_RESOURCE).asBoolean()) {
                Assert.assertTrue(acdKey + " -- " + prop.getName() + " resource", expectedDef.expectResource);
                foundResource = true;
            }
            ModelNode attrs = pathResult.get(ATTRIBUTES);
            if (attrs.isDefined() && attrs.asInt() > 0) {
                Assert.assertTrue(acdKey + " -- " + prop.getName() + " attributes = " + attrs.asString(), expectedDef.expectAttributes);
                foundAttr = true;
            }
            ModelNode ops = pathResult.get(OPERATIONS);
            if (ops.isDefined() && ops.asInt() > 0) {
                Assert.assertTrue(acdKey + " -- " + prop.getName() + " operations = " + ops.asString(), expectedDef.expectOps);
                foundOps = true;
            }
        }

        Assert.assertEquals(acdKey + " -- resource", expectedDef.expectResource, foundResource);
        Assert.assertEquals(acdKey + " -- attributes", expectedDef.expectAttributes, foundAttr);
        Assert.assertEquals(acdKey + " -- operations", expectedDef.expectOps, foundOps);
    }
}
 
Example 17
Source File: ModelHarmonizer.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void harmonizeModel(ModelVersion modelVersion, ModelNode source, ModelNode target) {
    if (source.getType() == ModelType.OBJECT && source.asInt() == 0 && !target.isDefined()) {
        target.setEmptyObject();
    }
}
 
Example 18
Source File: OperationCancellationUnitTestCase.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) {

    String name = operation.require(NAME).asString();

    goodHandlerLatch.countDown();

    ModelNode model = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS).getModel();
    ModelNode attr = model.get(name);
    final int current = attr.asInt();
    attr.set(operation.require(VALUE));

    context.getResult().set(current);

    context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
 
Example 19
Source File: OperationValidator.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void checkType(final ModelType modelType, final ModelNode value) {
    ModelNode resolved;
    try {
        resolved = expressionResolver.resolveExpressions(value);
    } catch (OperationFailedException e) {
        // Dealing with an unresolvable expression is beyond what this class can do.
        // So fall through and see what happens. Basically if modelType is EXPRESSION or STRING
        // it will pass, otherwise an IAE will be thrown
        resolved = value;
    }
    switch (modelType) {
        case BIG_DECIMAL:
            resolved.asBigDecimal();
            break;
        case BIG_INTEGER:
            resolved.asBigInteger();
            break;
        case BOOLEAN:
            resolved.asBoolean();
            break;
        case BYTES:
            resolved.asBytes();
            break;
        case DOUBLE:
            resolved.asDouble();
            break;
        case EXPRESSION:
            value.asString();
            break;
        case INT:
            resolved.asInt();
            break;
        case LIST:
            value.asList();
            break;
        case LONG:
            resolved.asLong();
            break;
        case OBJECT:
            value.asObject();
            break;
        case PROPERTY:
            value.asProperty();
            break;
        case STRING:
            value.asString();
            break;
        case TYPE:
            resolved.asType();
            break;
    }
}
 
Example 20
Source File: QueryOperationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static boolean matchesFilter(final ModelNode resource, final ModelNode filter, final Operator operator) throws OperationFailedException {
    boolean isMatching = false;
    List<Property> filterProperties = filter.asPropertyList();
    List<Boolean> matches = new ArrayList<>(filterProperties.size());

    for (Property property : filterProperties) {

        final String filterName = property.getName();
        final ModelNode filterValue = property.getValue();

        boolean isEqual = false;

        if(!filterValue.isDefined() || filterValue.asString().equals(UNDEFINED))  {
            // query for undefined attributes
            isEqual = !resource.get(filterName).isDefined();
        }  else {

            final ModelType targetValueType = resource.get(filterName).getType();

            try {
                // query for attribute values (throws exception when types don't match)
                switch (targetValueType) {
                    case BOOLEAN:
                        isEqual = filterValue.asBoolean() == resource.get(filterName).asBoolean();
                        break;
                    case LONG:
                        isEqual = filterValue.asLong() == resource.get(filterName).asLong();
                        break;
                    case INT:
                        isEqual = filterValue.asInt() == resource.get(filterName).asInt();
                        break;
                    case DOUBLE:
                        isEqual = filterValue.asDouble() == resource.get(filterName).asDouble();
                        break;
                    default:
                        isEqual = filterValue.equals(resource.get(filterName));
                }
            } catch (IllegalArgumentException e) {
                throw ControllerLogger.MGMT_OP_LOGGER.selectFailedCouldNotConvertAttributeToType(filterName, targetValueType);
            }

        }

        if(isEqual) {
            matches.add(resource.get(filterName).equals(filterValue));
        }

    }

    if (Operator.AND.equals(operator)) {
        // all matches must be true
        isMatching = matches.size() == filterProperties.size();

    } else if(Operator.OR.equals(operator)){
        // at least one match must be true
        for (Boolean match : matches) {
            if (match) {
                isMatching = true;
                break;
            }
        }
    }
    else {
        // This is just to catch programming errors where a new case isn't added above
        throw new IllegalArgumentException(
                ControllerLogger.MGMT_OP_LOGGER.invalidValue(
                        operator.toString(),
                        OPERATOR,
                        Arrays.asList(Operator.values())
                )
        );
    }


    return isMatching;
}