Java Code Examples for org.springframework.util.Assert#isAssignable()

The following examples show how to use org.springframework.util.Assert#isAssignable() . 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: HandlerMethodInvoker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Class<?> getHttpEntityType(MethodParameter methodParam) {
	Assert.isAssignable(HttpEntity.class, methodParam.getParameterType());
	ParameterizedType type = (ParameterizedType) methodParam.getGenericParameterType();
	if (type.getActualTypeArguments().length == 1) {
		Type typeArgument = type.getActualTypeArguments()[0];
		if (typeArgument instanceof Class) {
			return (Class<?>) typeArgument;
		}
		else if (typeArgument instanceof GenericArrayType) {
			Type componentType = ((GenericArrayType) typeArgument).getGenericComponentType();
			if (componentType instanceof Class) {
				// Surely, there should be a nicer way to do this
				Object array = Array.newInstance((Class<?>) componentType, 0);
				return array.getClass();
			}
		}
	}
	throw new IllegalArgumentException(
			"HttpEntity parameter (" + methodParam.getParameterName() + ") is not parameterized");

}
 
Example 2
Source File: ProtocolPluginHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Plugin plugin) {
    try {
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin, this.getClass().getClassLoader());

        final Class<?> protocolClass = classloader.loadClass(plugin.clazz());
        LOGGER.info("Register a new protocol plugin: {} [{}]", plugin.id(), plugin.clazz());

        Assert.isAssignable(Protocol.class, protocolClass);

        Protocol protocol = createInstance((Class<Protocol>) protocolClass);

        protocolPluginManager.register(new ProtocolDefinition(protocol, plugin));
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while router protocol instance", iae);
    }

}
 
Example 3
Source File: CertificatePluginHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Plugin plugin) {
    try {
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin, this.getClass().getClassLoader());

        final Class<?> certificateClass = classloader.loadClass(plugin.clazz());
        LOGGER.info("Register a new certificate plugin: {} [{}]", plugin.id(), plugin.clazz());

        Assert.isAssignable(Certificate.class, certificateClass);

        Certificate certificate = createInstance((Class<Certificate>) certificateClass);
        certificatePluginManager.register(new CertificateDefinition(certificate, plugin));
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while create certificate instance", iae);
    }
}
 
Example 4
Source File: TypeMappedAnnotation.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName, Class<T> type)
		throws NoSuchElementException {

	int attributeIndex = getAttributeIndex(attributeName, true);
	Method attribute = this.mapping.getAttributes().get(attributeIndex);
	Assert.notNull(type, "Type must not be null");
	Assert.isAssignable(type, attribute.getReturnType(),
			() -> "Attribute " + attributeName + " type mismatch:");
	return (MergedAnnotation<T>) getRequiredValue(attributeIndex, attributeName);
}
 
Example 5
Source File: AbstractContextLoader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
		MergedContextConfiguration mergedConfig) {
	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = mergedConfig.getContextInitializerClasses();
	if (initializerClasses.isEmpty()) {
		// no ApplicationContextInitializers have been declared -> nothing to do
		return;
	}

	List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();
	Class<?> contextClass = context.getClass();

	for (Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
			ApplicationContextInitializer.class);
		Assert.isAssignable(initializerContextClass, contextClass, String.format(
			"Could not add context initializer [%s] since its generic parameter [%s] "
					+ "is not assignable from the type of application context used by this "
					+ "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
			contextClass.getName()));
		initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(initializerInstances);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
		initializer.initialize(context);
	}
}
 
Example 6
Source File: TestUtils.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T getPropertyValue(Object root, String propertyPath,
		Class<T> type) {
	Object value = getPropertyValue(root, propertyPath);
	if (value != null) {
		Assert.isAssignable(type, value.getClass());
	}
	return (T) value;
}
 
Example 7
Source File: TypeDescriptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Cast this {@link TypeDescriptor} to a superclass or implemented interface
 * preserving annotations and nested type context.
 * @param superType the super type to cast to (can be {@code null})
 * @return a new TypeDescriptor for the up-cast type
 * @throws IllegalArgumentException if this type is not assignable to the super-type
 * @since 3.2
 */
@Nullable
public TypeDescriptor upcast(@Nullable Class<?> superType) {
	if (superType == null) {
		return null;
	}
	Assert.isAssignable(superType, getType());
	return new TypeDescriptor(getResolvableType().as(superType), superType, getAnnotations());
}
 
Example 8
Source File: TypeMappedAnnotation.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(
		String attributeName, Class<T> type) throws NoSuchElementException {

	int attributeIndex = getAttributeIndex(attributeName, true);
	Method attribute = this.mapping.getAttributes().get(attributeIndex);
	Class<?> componentType = attribute.getReturnType().getComponentType();
	Assert.notNull(type, "Type must not be null");
	Assert.notNull(componentType, () -> "Attribute " + attributeName + " is not an array");
	Assert.isAssignable(type, componentType, () -> "Attribute " + attributeName + " component type mismatch:");
	return (MergedAnnotation<T>[]) getRequiredValue(attributeIndex, attributeName);
}
 
Example 9
Source File: AbstractCondition.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
protected Object getParameterByIndex(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  Assert.isAssignable(AggregateQueryMethodConditionContext.class, conditionContext.getClass());
  AggregateQueryMethodConditionContext ctx = (AggregateQueryMethodConditionContext) conditionContext;
  List<Object> parameters = ctx.getParameterValues();
  int parameterIndex = getParameterIndex(annotatedTypeMetadata);
  int paramCount = parameters.size();
  if (parameterIndex < paramCount) {
    return parameters.get(parameterIndex);
  }
  throw new IllegalArgumentException("Argument index " + parameterIndex + " out of bounds, max count: " + paramCount);
}
 
Example 10
Source File: Jackson2CborDecoder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public Jackson2CborDecoder(ObjectMapper mapper, MimeType... mimeTypes) {
	super(mapper, mimeTypes);
	Assert.isAssignable(CBORFactory.class, mapper.getFactory().getClass());
}
 
Example 11
Source File: Jackson2SmileDecoder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public Jackson2SmileDecoder(ObjectMapper mapper, MimeType... mimeTypes) {
	super(mapper, mimeTypes);
	Assert.isAssignable(SmileFactory.class, mapper.getFactory().getClass());
}
 
Example 12
Source File: AbstractBeanFactory.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
	Assert.notNull(requiredType, "Required type must not be null");
	Assert.isAssignable(PropertyEditor.class, propertyEditorClass);
	this.customEditors.put(requiredType, propertyEditorClass);
}
 
Example 13
Source File: MappingJackson2XmlHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * The {@code objectMapper} parameter must be a {@link XmlMapper} instance.
 */
@Override
public void setObjectMapper(ObjectMapper objectMapper) {
	Assert.isAssignable(XmlMapper.class, objectMapper.getClass());
	super.setObjectMapper(objectMapper);
}
 
Example 14
Source File: RepositoryPluginHandler.java    From gravitee-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(Plugin plugin) {
    try {
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin, this.getClass().getClassLoader());

        final Class<?> repositoryClass = classloader.loadClass(plugin.clazz());
        LOGGER.info("Register a new repository plugin: {} [{}]", plugin.id(), plugin.clazz());

        Assert.isAssignable(Repository.class, repositoryClass);

        Repository repository = createInstance((Class<Repository>) repositoryClass);
        for(Scope scope : repository.scopes()) {
            if (! repositories.containsKey(scope)) {
                String requiredRepositoryType = repositoryTypeByScope.get(scope);

                // Load only repository plugin for a given scope (provided in the configuration)
                if (repository.type().equalsIgnoreCase(requiredRepositoryType)) {
                    boolean loaded = false;
                    int tries = 0;

                    while (! loaded) {
                        if (tries > 0) {
                            // Wait for 5 seconds before giving an other try
                            Thread.sleep(5000);
                        }
                        loaded = loadRepository(scope, repository, plugin);
                        tries++;


                        if (! loaded) {
                            LOGGER.error("Unable to load repository {} for scope {}. Retry in 5 seconds...", scope, plugin.id());
                        }
                    }
                } else {
                    LOGGER.debug("Scoped repository [{}] must be loaded by {}. Skipping registration",
                            scope, requiredRepositoryType);
                }
            } else {
                LOGGER.warn("Repository scope {} already loaded by {}", scope,
                        repositories.get(scope));
            }
        }
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while create repository instance", iae);
    }
}
 
Example 15
Source File: Jackson2SmileEncoder.java    From java-technology-stack with MIT License 4 votes vote down vote up
public Jackson2SmileEncoder(ObjectMapper mapper, MimeType... mimeTypes) {
	super(mapper, mimeTypes);
	Assert.isAssignable(SmileFactory.class, mapper.getFactory().getClass());
	setStreamingMediaTypes(Collections.singletonList(new MediaType("application", "stream+x-jackson-smile")));
}
 
Example 16
Source File: ComponentScanAnnotationParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {
	List<TypeFilter> typeFilters = new ArrayList<TypeFilter>();
	FilterType filterType = filterAttributes.getEnum("type");

	for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
		switch (filterType) {
			case ANNOTATION:
				Assert.isAssignable(Annotation.class, filterClass,
						"@ComponentScan ANNOTATION type filter requires an annotation type");
				@SuppressWarnings("unchecked")
				Class<Annotation> annotationType = (Class<Annotation>) filterClass;
				typeFilters.add(new AnnotationTypeFilter(annotationType));
				break;
			case ASSIGNABLE_TYPE:
				typeFilters.add(new AssignableTypeFilter(filterClass));
				break;
			case CUSTOM:
				Assert.isAssignable(TypeFilter.class, filterClass,
						"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
				TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
				ParserStrategyUtils.invokeAwareMethods(
						filter, this.environment, this.resourceLoader, this.registry);
				typeFilters.add(filter);
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
		}
	}

	for (String expression : filterAttributes.getStringArray("pattern")) {
		switch (filterType) {
			case ASPECTJ:
				typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
				break;
			case REGEX:
				typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
		}
	}

	return typeFilters;
}
 
Example 17
Source File: AbstractEntityManagerFactoryBean.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Set the PersistenceProvider implementation class to use for creating the
 * EntityManagerFactory. If not specified, the persistence provider will be
 * taken from the JpaVendorAdapter (if any) or retrieved through scanning
 * (as far as possible).
 * @see JpaVendorAdapter#getPersistenceProvider()
 * @see javax.persistence.spi.PersistenceProvider
 * @see javax.persistence.Persistence
 */
public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) {
	Assert.isAssignable(PersistenceProvider.class, persistenceProviderClass);
	this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass);
}
 
Example 18
Source File: BeanUtils.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Instantiate a class using its no-arg constructor and return the new instance
 * as the specified assignable type.
 * <p>Useful in cases where the type of the class to instantiate (clazz) is not
 * available, but the type desired (assignableTo) is known.
 * <p>Note that this method tries to set the constructor accessible if given a
 * non-accessible (that is, non-public) constructor.
 * @param clazz class to instantiate
 * @param assignableTo type that clazz must be assignableTo
 * @return the new instance
 * @throws BeanInstantiationException if the bean cannot be instantiated
 * @see Constructor#newInstance
 */
@SuppressWarnings("unchecked")
public static <T> T instantiateClass(Class<?> clazz, Class<T> assignableTo) throws BeanInstantiationException {
	Assert.isAssignable(assignableTo, clazz);
	return (T) instantiateClass(clazz);
}
 
Example 19
Source File: BeanUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Instantiate a class using its no-arg constructor and return the new instance
 * as the specified assignable type.
 * <p>Useful in cases where the type of the class to instantiate (clazz) is not
 * available, but the type desired (assignableTo) is known.
 * <p>Note that this method tries to set the constructor accessible if given a
 * non-accessible (that is, non-public) constructor.
 * @param clazz class to instantiate
 * @param assignableTo type that clazz must be assignableTo
 * @return the new instance
 * @throws BeanInstantiationException if the bean cannot be instantiated
 * @see Constructor#newInstance
 */
@SuppressWarnings("unchecked")
public static <T> T instantiateClass(Class<?> clazz, Class<T> assignableTo) throws BeanInstantiationException {
	Assert.isAssignable(assignableTo, clazz);
	return (T) instantiateClass(clazz);
}
 
Example 20
Source File: BeanUtils.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Instantiate a class using its no-arg constructor and return the new instance
 * as the specified assignable type.
 * <p>Useful in cases where the type of the class to instantiate (clazz) is not
 * available, but the type desired (assignableTo) is known.
 * <p>Note that this method tries to set the constructor accessible if given a
 * non-accessible (that is, non-public) constructor.
 * @param clazz class to instantiate
 * @param assignableTo type that clazz must be assignableTo
 * @return the new instance
 * @throws BeanInstantiationException if the bean cannot be instantiated
 * @see Constructor#newInstance
 */
@SuppressWarnings("unchecked")
public static <T> T instantiateClass(Class<?> clazz, Class<T> assignableTo) throws BeanInstantiationException {
	Assert.isAssignable(assignableTo, clazz);
	return (T) instantiateClass(clazz);
}