Example usage for org.apache.commons.lang3.reflect TypeUtils isInstance

List of usage examples for org.apache.commons.lang3.reflect TypeUtils isInstance

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect TypeUtils isInstance.

Prototype

public static boolean isInstance(final Object value, final Type type) 

Source Link

Document

Checks if the given value can be assigned to the target type following the Java generics rules.

Usage

From source file:co.runrightfast.component.events.impl.ComponentEventImpl.java

/**
 *
 * @param componentId required/*  ww w .j a  v  a 2s  .  c  o  m*/
 * @param id optional - new id generated if not supplied
 * @param eventTimestamp optional - uses now if not specified
 * @param jvmId optional - uses {@link AppUtils#JVM_ID} if not specified
 * @param event required
 * @param data conditionally required based on event
 * @param exception optional
 * @param tags optional
 */
public ComponentEventImpl(@NonNull final ComponentId componentId, final UUID id, final Instant eventTimestamp,
        final String jvmId, @NonNull final Event<DATA> event, final Optional<DATA> data,
        final Optional<Throwable> exception, final Optional<Set<String>> tags) {

    if (event.eventDataType().isPresent()) {
        checkArgument(data != null && data.isPresent(), "event is expecting data : event=%s", event.name());
        checkArgument(TypeUtils.isInstance(data.get(), event.eventDataType().get()),
                "event data type does not match : event=%s, expected=%s, actual=%s", event.name(),
                event.eventDataType().get(), data.get().getClass());
    } else {
        checkArgument(data == null || !data.isPresent(), "event is not expecting data : event=%s",
                event.name());
    }

    this.componentId = componentId;
    this.id = id != null ? id : UUID.randomUUID();
    this.eventTimestamp = eventTimestamp != null ? eventTimestamp : Instant.now();
    this.jvmId = StringUtils.isNotBlank(jvmId) ? jvmId : AppUtils.JVM_ID;
    this.event = event;
    this.data = data != null ? data : Optional.empty();
    this.exception = exception != null ? exception : Optional.empty();
    this.tags = tags != null ? tags : Optional.empty();
}

From source file:com.xpn.xwiki.internal.filter.output.UserInstanceOutputFilterStream.java

private <T> T get(Type type, String key, FilterEventParameters parameters, T def) {
    if (!parameters.containsKey(key)) {
        return def;
    }//from  w  w  w . ja  v  a2  s  .  c  om

    Object value = parameters.get(key);

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

    if (TypeUtils.isInstance(value, type)) {
        return (T) value;
    }

    return this.converter.convert(type, value);
}

From source file:com.xpn.xwiki.internal.filter.output.AbstractEntityOutputFilterStream.java

protected <T> T get(Type type, String key, FilterEventParameters parameters, T def, boolean replaceNull,
        boolean convert) {
    if (parameters == null) {
        return def;
    }/*from   w  w w  .j a  v  a  2  s.  co  m*/

    if (!parameters.containsKey(key)) {
        return def;
    }

    Object value = parameters.get(key);

    if (value == null) {
        return replaceNull ? def : null;
    }

    if (TypeUtils.isInstance(value, type)) {
        return (T) value;
    }

    return convert ? this.converter.convert(type, value) : (T) value;
}

From source file:org.apache.bval.jsr.ConstraintAnnotationAttributes.java

/**
 * Get the value of <code>this.attributeName</code> from <code>map</code>.
 * /* w  w w.jav  a2  s .  c om*/
 * @param <V>
 * @param map
 * @return V if you say so
 */
public <V> V get(Map<? super String, ? super V> map) {
    @SuppressWarnings("unchecked")
    final V result = (V) map.get(getAttributeName());
    if (TypeUtils.isInstance(result, getType())) {
        return result;
    }
    throw new IllegalStateException(String.format("Invalid '%s' value: %s", getAttributeName(), result));
}

From source file:org.apache.bval.util.KeyedAccess.java

/**
 * {@inheritDoc}/*ww  w.  ja  va 2 s  .c  o  m*/
 */
@Override
public Object get(Object instance) {
    if (instance instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) instance;
        Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(containerType, Map.class);
        Type keyType = TypeUtils.unrollVariables(typeArguments, MAP_TYPEVARS[0]);
        if (key == null || keyType == null || TypeUtils.isInstance(key, keyType)) {
            return map.get(key);
        }
        if (key instanceof String) {
            String name = (String) key;
            Class<?> rawKeyType = TypeUtils.getRawType(keyType, containerType);
            if (rawKeyType.isEnum()) {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                final Object result = map.get(Enum.valueOf((Class<? extends Enum>) rawKeyType, name));
                return result;
            }
            for (Map.Entry<?, ?> e : map.entrySet()) {
                if (name.equals(e.getKey())) {
                    return e.getValue();
                }
            }
        }
    }
    return null;
}

From source file:org.wrml.runtime.format.ParserModelGraph.java

/**
 * Process a "raw" value (from a serialized model graph) into one that is
 * ready for the runtime./*from  ww w .j  av a  2s. c o  m*/
 *
 * @param rawValue The "raw" value to process. A raw value is used in
 *                 serialization of model graphs.
 * @return The processed value, ready for runtime.
 */
@SuppressWarnings("unchecked")
public Object endValue(final Object rawValue) {

    /*
     * As a special case for in-line model typing, WRML allows the
     * "schemaUri" slot to be present "on the wire". This slot is
     * "dimensional" in nature, so we will store it in the dimensions
     * instead of the model itself.
     * 
     * Compare the slot's name and update the Dimensions accordingly.
     */
    if (!_SlotNameStack.isEmpty() && _SlotNameStack.peek().equals(Model.SLOT_NAME_SCHEMA_URI)) {
        _DimensionsBuilderStack.peek().setSchemaUri(URI.create(String.valueOf(rawValue)));
        _SlotNameStack.pop();
        return null;
    }

    Object runtimeValue = null;
    boolean isModel = false;
    if (rawValue != null && rawValue instanceof Model) {
        isModel = true;

        /*
         * Convert "raw" (undefined) model values here to handle the root
         * model case.
         */
        runtimeValue = convertRawModelValue((Model) rawValue);
    }

    if (!_ScopeStack.isEmpty()) {
        if (rawValue != null) {
            if (TypeUtils.isInstance(rawValue, String.class)) {
                runtimeValue = convertRawStringValue((String) rawValue);
            } else if (TypeUtils.isInstance(rawValue, Integer.class)) {
                runtimeValue = convertRawIntegerValue((Integer) rawValue);
            } else if (TypeUtils.isInstance(rawValue, List.class)) {
                runtimeValue = convertRawListValue((List<Object>) rawValue);
            } else if (!isModel) {
                /*
                 * The other "raw" types are equivalent to their "runtime" type
                 * counterparts; no conversion necessary.
                 */
                runtimeValue = rawValue;
            }
        }

        final ScopeType scopeType = _ScopeStack.peek();

        switch (scopeType) {
        case Model: {
            /*
             * The graph is focused on the parent model; meaning that a slot
             * should be set.
             */
            final Model parentModel = _ModelStack.peek();
            final String slotName = _SlotNameStack.peek();

            if (!slotName.equals(Model.SLOT_NAME_HEAP_ID)) {
                parentModel.getSlotMap().put(slotName, runtimeValue);
            } else if (runtimeValue != null) {

                // Remove the started model from the stack
                _ModelStack.pop();
                // Push this model onto the stack
                final Model m = (Model) runtimeValue;
                _ModelStack.push(m);
            }

            /*
             * Now finished with this slot, shift focus.
             */
            _SlotNameStack.pop();

            break;
        }
        case List: {

            /*
             * The graph is focused on a list; meaning that an element
             * should be added.
             */

            final List<Object> list = _ListStack.peek();
            list.add(runtimeValue);

            break;
        }

        } // End of switch
    }

    return runtimeValue;
}

From source file:org.xwiki.filter.instance.internal.output.XWikiDocumentOutputFilterStream.java

private <T> T get(Type type, String key, FilterEventParameters parameters, T def, boolean replaceNull) {
    if (!parameters.containsKey(key)) {
        return def;
    }//from  w w  w.  j  av a  2s.c  o m

    Object value = parameters.get(key);

    if (value == null) {
        return replaceNull ? def : null;
    }

    if (TypeUtils.isInstance(value, type)) {
        return (T) value;
    }

    return this.converter.convert(type, value);
}

From source file:therian.Operation.java

/**
 * Learn whether {@code operator} seems to implement {@code this}.
 *
 * @param operator to check//w w  w  . j  a  va  2  s.  c  o  m
 * @return boolean
 */
public boolean matches(Operator<?> operator) {
    final Type expectedType = TypeUtils.unrollVariables(
            TypeUtils.getTypeArguments(operator.getClass(), Operator.class),
            Operator.class.getTypeParameters()[0]);

    if (!TypeUtils.isInstance(this, expectedType)) {
        return false;
    }

    final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(expectedType, Operation.class);
    for (Class<?> c : ClassUtils.hierarchy(TypeUtils.getRawType(expectedType, operator.getClass()))) {
        if (c.equals(Operation.class)) {
            break;
        }
        for (TypeVariable<?> var : c.getTypeParameters()) {
            Type type = Types.resolveAt(this, var, typeArguments);
            if (type == null || typeArguments == null) {
                continue;
            }
            if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
                type = ClassUtils.primitiveToWrapper((Class<?>) type);
            }
            if (!TypeUtils.isAssignable(type, TypeUtils.unrollVariables(typeArguments, var))) {
                return false;
            }
        }
    }
    return true;
}

From source file:therian.operator.add.AddEntryToMap.java

@Override
public boolean supports(TherianContext context, Add<? extends Map.Entry, ? extends Map> add) {
    // cannot add to immutable types
    if (context.eval(ImmutableCheck.of(add.getTargetPosition())).booleanValue()) {
        return false;
    }//from  w  w  w.ja v a 2  s  . c  o  m
    if (add.getSourcePosition().getValue() == null) {
        return false;
    }
    final Map<TypeVariable<?>, Type> targetArgs = TypeUtils.getTypeArguments(add.getTargetType().getType(),
            Map.class);

    final Type targetKeyType = TypeUtils.unrollVariables(targetArgs, Map.class.getTypeParameters()[0]);

    if (targetKeyType != null
            && !TypeUtils.isInstance(add.getSourcePosition().getValue().getKey(), targetKeyType)) {
        return false;
    }
    final Type targetValueType = TypeUtils.unrollVariables(targetArgs, Map.class.getTypeParameters()[1]);

    return targetValueType == null
            || TypeUtils.isInstance(add.getSourcePosition().getValue().getValue(), targetValueType);
}

From source file:therian.operator.add.AddToArray.java

@Override
public boolean supports(TherianContext context, Add<?, ?> add) {
    if (!(TypeUtils.isArrayType(add.getTargetPosition().getType())
            && Positions.isWritable(add.getTargetPosition()))) {
        return false;
    }/*from   w  w w.  j av  a2  s.  co m*/
    final Type targetElementType = context.eval(GetElementType.of(add.getTargetPosition()));
    return TypeUtils.isInstance(add.getSourcePosition().getValue(), targetElementType);
}