Java Code Examples for org.apache.commons.lang3.reflect.TypeUtils

The following examples show how to use org.apache.commons.lang3.reflect.TypeUtils. These examples are extracted from open source projects. 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 Project: arcusplatform   Source File: TypeCoercerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSupportedType(Class<?> clazz, Type type) {
   if (type == null) {
      return false;
   }
   if (TypeUtils.isAssignable(type, clazz)) {
      return true;
   }
   TypeHandler<?> handler = getHandler(clazz);
   if (handler != null) {
      return handler.isSupportedType(type);
   }
   if (clazz.isEnum()) {
      return enumHandler.isSupportedType(clazz, type);
   }
   return false;
}
 
Example 2
Source Project: arcusplatform   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
private static Type doDeserializeType(String name) {
   int startIdx = name.indexOf('<');
   if(startIdx == -1) {
      return classForName(name);
   }
   else if(name.charAt(name.length() - 1) == '>') {
      Class<?> rawType = classForName(name.substring(0, startIdx));
      String [] typeNames = StringUtils.split(name.substring(startIdx+1, name.length() - 1), ',');
      Type [] typeParameters = new Type[typeNames.length];
      for(int i=0; i<typeNames.length; i++) {
         typeParameters[i] = doDeserializeType(typeNames[i]);
      }
      return TypeUtils.parameterize(rawType, typeParameters);
   }
   else {
      throw new IllegalArgumentException("Invalid class name, missing close '>': " + name);
   }
}
 
Example 3
Source Project: yare   Source File: RuntimeRulesBuilder.java    License: MIT License 6 votes vote down vote up
@Override
public ValueProvider create(String name, Type baseReferenceType, Type referenceType, String reference) {
    String referenceName = reference;
    String path = null;

    int dotIndex = reference.indexOf('.');
    if (dotIndex > -1) {
        referenceName = reference.substring(0, dotIndex);
        path = reference.substring(dotIndex + 1);
    }

    return ValueProviderFactory.createFromPath(
            TypeUtils.getRawType(baseReferenceType, null),
            referenceName,
            TypeUtils.getRawType(referenceType, null),
            path);
}
 
Example 4
private Class<? extends Throwable> getGenericType(Class<? extends JsonApiExceptionMapper> mapper) {
  Type[] types = mapper.getGenericInterfaces();
  if (null == types || 0 == types.length ){
    types = new Type[]{mapper.getGenericSuperclass()};
  }

  for (Type type : types) {
    if (type instanceof ParameterizedType && (TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),JsonApiExceptionMapper.class)
        || TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),ExceptionMapper.class))) {
      //noinspection unchecked
      return (Class<? extends Throwable>) ((ParameterizedType) type).getActualTypeArguments()[0];
    }
  }
  //Won't get in here
  return null;
}
 
Example 5
Source Project: cloudbreak   Source File: FreeIpaClient.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<User> userFind(String user) throws FreeIpaClientException {
    List<Object> flags = List.of(user);
    Map<String, Object> params = Map.of(
            "uid", user,
            "all", true
    );
    ParameterizedType type = TypeUtils
            .parameterize(List.class, User.class);
    List<User> foundUsers = (List<User>) invoke("user_find", flags, params, type).getResult();
    if (foundUsers.size() > 1) {
        LOGGER.error("Found more than 1 user with uid {}.", user);
    }
    if (foundUsers.isEmpty()) {
        return Optional.empty();
    } else {
        return Optional.of(foundUsers.get(0));
    }
}
 
Example 6
private Property readAsPropertyIfPrimitive(Type type) {
    if (com.github.kongchen.swagger.docgen.util.TypeUtils.isPrimitive(type)) {
        return ModelConverters.getInstance().readAsProperty(type);
    } else {
        String msg = String.format("Non-primitive type: %s used as request/path/cookie parameter", type);
        log.warn(msg);

        // fallback to string if type is simple wrapper for String to support legacy code
        JavaType ct = constructType(type);
        if (isSimpleWrapperForString(ct.getRawClass())) {
            log.warn(String.format("Non-primitive type: %s used as string for request/path/cookie parameter", type));
            return new StringProperty();
        }
    }
    return null;
}
 
Example 7
@Override
public boolean shouldIgnoreType(Type type, Set<Type> typesToSkip) {
    Class<?> clazz = TypeUtils.getRawType(type, type);
    if (clazz == null) {
        return false;
    }

    String clazzName = clazz.getName();

    switch (clazzName) {
        case "javax.servlet.ServletRequest":
        case "javax.servlet.ServletResponse":
        case "javax.servlet.http.HttpSession":
        case "javax.servlet.http.PushBuilder":
        case "java.security.Principal":
        case "java.io.OutputStream":
        case "java.io.Writer":
            return true;
        default:
    }

    return clazzName.startsWith("org.springframework") &&
            !"org.springframework.web.multipart.MultipartFile".equals(clazzName);
}
 
Example 8
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) {
    Class<?> cls = TypeUtils.getRawType(type, type);

    if (shouldIgnoreClass(cls) || typesToSkip.contains(type)) {
        // stop the processing chain
        typesToSkip.add(type);
        return Lists.newArrayList();
    }
    for (Annotation annotation : annotations) {
        if (annotation instanceof BeanParam || annotation instanceof InjectParam) {
            return reader.extractTypes(cls, typesToSkip, Lists.newArrayList());
        }
    }
    return super.extractParameters(annotations, type, typesToSkip, chain);
}
 
Example 9
Source Project: mPaaS   Source File: ReflectUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将type中的变量参数实例化
 *
 * @param type
 * @param resolver
 *            将变量转换成实际的类的方法
 * @return
 */
public static Type parameterize(Type type,
                                Function<TypeVariable<?>, Type> resolver) {
    // 类:String
    if (type instanceof Class) {
        return type;
    }
    // 变量:E
    if (type instanceof TypeVariable) {
        return resolver.apply((TypeVariable<?>) type);
    }
    // 泛型:List<E>
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        Type[] oriTypes = paramType.getActualTypeArguments();
        // 若参数中出现了泛型或变量则使用递归
        boolean recursion = false;
        for (Type oriType : oriTypes) {
            if (!(oriType instanceof Class)) {
                recursion = true;
                break;
            }
        }
        if (recursion) {
            Type[] actTypes = new Type[oriTypes.length];
            for (int i = 0; i < oriTypes.length; i++) {
                actTypes[i] = parameterize(oriTypes[i], resolver);
            }
            return TypeUtils.parameterize((Class<?>) paramType.getRawType(),
                    actTypes);
        } else {
            return type;
        }
    }
    throw new RuntimeException("不支持的参数类型:" + type.getClass().getName());
}
 
Example 10
Source Project: mPass   Source File: ReflectUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将type中的变量参数实例化
 * 
 * @param type
 * @param resolver
 *            将变量转换成实际的类的方法
 * @return
 */
public static Type parameterize(Type type,
		Function<TypeVariable<?>, Type> resolver) {
	// 类:String
	if (type instanceof Class) {
		return type;
	}
	// 变量:E
	if (type instanceof TypeVariable) {
		return resolver.apply((TypeVariable<?>) type);
	}
	// 泛型:List<E>
	if (type instanceof ParameterizedType) {
		ParameterizedType paramType = (ParameterizedType) type;
		Type[] oriTypes = paramType.getActualTypeArguments();
		// 若参数中出现了泛型或变量则使用递归
		boolean recursion = false;
		for (Type oriType : oriTypes) {
			if (!(oriType instanceof Class)) {
				recursion = true;
				break;
			}
		}
		if (recursion) {
			Type[] actTypes = new Type[oriTypes.length];
			for (int i = 0; i < oriTypes.length; i++) {
				actTypes[i] = parameterize(oriTypes[i], resolver);
			}
			return TypeUtils.parameterize((Class<?>) paramType.getRawType(),
					actTypes);
		} else {
			return type;
		}
	}
	throw new RuntimeException("不支持的参数类型:" + type.getClass().getName());
}
 
Example 11
/**
 * Parses a string into a type. Returns null if it doesn't succeed.
 * FIXME Only supports parameterized types with at most one type argument.
 * Doesn't support wildcard types.
 *
 * TODO make a real parser someday
 */
private static Type parseType(String t) {
    Matcher matcher = PARAM_TYPE_MATCHER.matcher(t.replaceAll("\\s+", ""));
    if (matcher.matches()) {
        String raw = matcher.group(1);
        Type result;
        try {
            result = ClassUtils.getClass(raw);
        } catch (ClassNotFoundException e) {
            return null;
        }

        String param = matcher.group(3);
        if (StringUtils.isNotBlank(param)) {
            Type paramType = parseType(param);
            if (paramType != null) {
                result = TypeUtils.parameterize((Class) result, paramType);
            }
        }

        String arrayDims = matcher.group(4);
        if (StringUtils.isNotBlank(arrayDims)) {
            int dimensions = StringUtils.countMatches(arrayDims, '[');
            while (dimensions-- > 0) {
                result = TypeUtils.genericArrayType(result);
            }
        }

        return result;
    }
    return null;
}
 
Example 12
Source Project: arcusplatform   Source File: PairingDeviceResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Function<? super PlatformMessage, ?> getResolverForParameter(Method method, Type parameter, Annotation[] annotations) {
	if(PairingDevice.class.equals(parameter)) {
		return this::findPairingDevice;
	}
	if(PersistentModelWrapper.class.equals(TypeUtils.getRawType(parameter, null)) && TypeUtils.isAssignable(PairingDeviceWrapper, parameter)) {
		return this::findPairingDeviceWrapper;
	}
	return null;
}
 
Example 13
Source Project: arcusplatform   Source File: TypeMarker.java    License: Apache License 2.0 5 votes vote down vote up
protected TypeMarker() {
   Map<TypeVariable<?>, Type> types = TypeUtils.getTypeArguments(this.getClass().getGenericSuperclass(), TypeMarker.class);
   if(types.isEmpty()) {
      throw new IllegalArgumentException("Improper use of TypeMarker, must specify a concrete (no ?s) type for the type variable");
   }
   this.type = types.values().iterator().next();
}
 
Example 14
Source Project: arcusplatform   Source File: TypeHandlerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSupportedType(Type type) {
   if (type == null) {
      return false;
   }
   if (TypeUtils.isAssignable(type, targetType)) {
      return true;
   }
   for (Class<?> clazz : supportedTypes) {
      if (TypeUtils.isAssignable(type, clazz)) {
         return true;
      }
   }
   return false;
}
 
Example 15
Source Project: arcusplatform   Source File: DriverMatchers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a definition and a value to a matcher.  If the value is null or not
 * set this will return {@code null}.  If the proper matcher can't be determined
 * this will return {@code null} and add the appropriate error to {@code v}.
 * @param def
 * @param value
 * @param v
 * @return
 */
public static Predicate<AttributeMap> toMatcher(AttributeDefinition def, Object value) {
   if(value == null) {
      return null;
   }
   AttributeKey<?> key = def.getKey();
   if(String.class.equals(key.getType())) {
      return toStringMatcher((AttributeKey<String>) key, value);
   }
   else if(Collection.class.isAssignableFrom(TypeUtils.getRawType(key.getType(), null))) {
      return toCollectionMatcher(
            // this cast should be safe since we're using it read-only
            // any class can be down-cast to Object on a get
            // sets would throw ClassCastException in most cases
            (AttributeKey<Collection<Object>>) key,
            AttributeTypes.extractContainedType(def.getAttributeType()), 
            value
      );
   }
   else if(ByteSet.class.equals(key.getType())) {
      return toByteSetMatcher((AttributeKey<ByteSet>) key, value);
   }
   else if(TypeUtils.getRawType(key.getType(), null).isAssignableFrom(value.getClass())) {
      return DriverPredicates.attributeEquals((AttributeKey) key, value);
   }
   else if(def.getAttributeType().isAssignableFrom(value.getClass())) {
      return DriverPredicates.attributeEquals((AttributeKey) key, def.getAttributeType().coerce(value));
   }
   else if(value instanceof Collection) {
      return toCollectionMatcher(key, def.getAttributeType(), value);
   }
   GroovyValidator.error("Unable to create a matcher for [" + key + "] unsupported type for matching");
   return null;
}
 
Example 16
Source Project: arcusplatform   Source File: DriverMatchers.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean addMatcherIf(AttributeMapPredicateBuilder builder, AttributeDefinition def, Object value, Validator v) {
   if(value == null) {
      return false;
   }
   AttributeKey<?> key = def.getKey();
   if(String.class.equals(key.getType())) {
      return addStringMatcher(builder, (AttributeKey<String>) key, value, v);
   }
   else if(Collection.class.isAssignableFrom(TypeUtils.getRawType(key.getType(), null))) {
      return addCollectionMatcher(builder,
            (AttributeKey<Collection<?>>) key,
            AttributeTypes.extractContainedType(def.getAttributeType()), value, v);
   }
   else if(ByteSet.class.equals(key.getType())) {
      return addByteSetMatcher(builder, (AttributeKey<ByteSet>) key, value, v);
   }
   else if(TypeUtils.getRawType(key.getType(), null).isAssignableFrom(value.getClass())) {
      builder.attribute((AttributeKey) key).equalTo(value);
      return true;
   }
   else if(def.getAttributeType().isAssignableFrom(value.getClass())) {
      builder.attribute((AttributeKey) key).equalTo(def.getAttributeType().coerce(value));
      return true;
   }
   else if(value instanceof Collection) {
      return addInCollectionMatcher(builder, key, def.getAttributeType(), value);
   }
   v.error("Unable to create a matcher for [" + key + "] unsupported type for matching");
   return false;
}
 
Example 17
Source Project: arcusplatform   Source File: AttributeKey.java    License: Apache License 2.0 5 votes vote down vote up
private static Type wrap(Type type) {
   if(type instanceof ParameterizedType) {
      ParameterizedType pType  = (ParameterizedType) type;
      // re-wrap in the internal representation of TypeUtils for equalities sake (and esp hashCode)
      type = TypeUtils.parameterize((Class<?>) pType.getRawType(), wrap(pType.getActualTypeArguments()));
   }
   return type;
}
 
Example 18
Source Project: arcusplatform   Source File: TestAttributeKey.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeSet() throws Exception {
   byte [] bytes = write(AttributeKey.createSetOf("ByteSet", Byte.class));
   AttributeKey<?> key = (AttributeKey<?>) read(bytes);
   assertEquals("ByteSet", key.getName());
   assertEquals(TypeUtils.parameterize(Set.class, Byte.class), key.getType());
}
 
Example 19
Source Project: arcusplatform   Source File: TestAttributeKey.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeList() throws Exception {
   byte [] bytes = write(AttributeKey.createListOf("StringList", String.class));
   AttributeKey<?> key = (AttributeKey<?>) read(bytes);
   assertEquals("StringList", key.getName());
   assertEquals(TypeUtils.parameterize(List.class, String.class), key.getType());
}
 
Example 20
Source Project: arcusplatform   Source File: TestAttributeKey.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeMap() throws Exception {
   byte [] bytes = write(AttributeKey.createMapOf("DateMap", Date.class));
   AttributeKey<?> key = (AttributeKey<?>) read(bytes);
   assertEquals("DateMap", key.getName());
   assertEquals(TypeUtils.parameterize(Map.class, String.class, Date.class), key.getType());
}
 
Example 21
Source Project: yare   Source File: EqZonedDateTime.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Eq.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null));

}
 
Example 22
Source Project: yare   Source File: ContainsAny.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return ContainsAny.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            Collection.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            Collection.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 23
Source Project: yare   Source File: GeZonedDateTime.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Ge.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 24
Source Project: yare   Source File: LtComparable.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Lt.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 25
Source Project: yare   Source File: GtComparable.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Gt.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 26
Source Project: yare   Source File: GeComparable.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Ge.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            Comparable.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 27
Source Project: yare   Source File: GtZonedDateTime.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Gt.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 28
Source Project: yare   Source File: ContainsAllInstance.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return ContainsAll.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            Collection.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            !Collection.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 29
Source Project: yare   Source File: LeZonedDateTime.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Le.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[0].getType(), null)) &&
            ZonedDateTime.class.isAssignableFrom(TypeUtils.getRawType(valueProviders[1].getType(), null));
}
 
Example 30
Source Project: yare   Source File: EqObjectArray.java    License: MIT License 5 votes vote down vote up
private boolean isApplicable(Expression.Operator operator, ValueProvider[] valueProviders) {
    return Eq.OPERATOR_NAME.equals(operator.getCall()) &&
            operator.getArguments().size() == 2 &&
            valueProviders.length == 2 &&
            TypeUtils.getRawType(valueProviders[0].getType(), null).isArray() &&
            TypeUtils.getRawType(valueProviders[1].getType(), null).isArray();
}