Example usage for org.springframework.util Assert isAssignable

List of usage examples for org.springframework.util Assert isAssignable

Introduction

In this page you can find the example usage for org.springframework.util Assert isAssignable.

Prototype

public static void isAssignable(Class<?> superType, @Nullable Class<?> subType,
        Supplier<String> messageSupplier) 

Source Link

Document

Assert that superType.isAssignableFrom(subType) is true .

Usage

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context./*from w ww . j ava 2 s .  c  o  m*/
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param servletContext the current servlet context
 * @param applicationContext the newly created application context
 * @see #createWebApplicationContext(ServletContext, ApplicationContext)
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses(
            servletContext);
    if (initializerClasses.size() == 0) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;
    }

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

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
                ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, contextClass,
                    String.format(
                            "Could not add context initializer [%s] as 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(BeanUtils.instantiateClass(initializerClass));
    }

    ConfigurableEnvironment env = applicationContext.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(servletContext, null);
    }

    Collections.sort(initializerInstances, new AnnotationAwareOrderComparator());
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(applicationContext);
    }
}

From source file:org.eclipse.gemini.blueprint.service.exporter.support.OsgiServiceFactoryBean.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(bundleContext, "required property 'bundleContext' has not been set");

    hasNamedBean = StringUtils.hasText(targetBeanName);

    Assert.isTrue(hasNamedBean || target != null,
            "Either 'targetBeanName' or 'target' properties have to be set.");

    // if we have a name, we need a bean factory
    if (hasNamedBean) {
        Assert.notNull(beanFactory, "Required property 'beanFactory' has not been set.");
    }/*from   w ww. j a v  a 2s . c  o  m*/

    // initialize bean only when dealing with singletons and named beans
    if (hasNamedBean) {
        Assert.isTrue(beanFactory.containsBean(targetBeanName),
                "Cannot locate bean named '" + targetBeanName + "' inside the running bean factory.");

        if (beanFactory.isSingleton(targetBeanName)) {
            if (beanFactory instanceof ConfigurableListableBeanFactory) {
                ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) beanFactory;
                BeanDefinition definition = clbf.getBeanDefinition(targetBeanName);
                if (!definition.isLazyInit()) {
                    target = beanFactory.getBean(targetBeanName);
                    targetClass = target.getClass();
                }
            }
        }

        if (targetClass == null) {
            // lazily get the target class
            targetClass = beanFactory.getType(targetBeanName);
        }

        // when running inside a container, add the dependency between this bean and the target one
        addBeanFactoryDependency();
    } else {
        targetClass = target.getClass();
    }

    if (propertiesResolver == null) {
        propertiesResolver = new BeanNameServicePropertiesResolver();
        ((BeanNameServicePropertiesResolver) propertiesResolver).setBundleContext(bundleContext);
    }

    // sanity check
    if (interfaces == null) {
        if (DefaultInterfaceDetector.DISABLED.equals(interfaceDetector))
            throw new IllegalArgumentException(
                    "No service interface(s) specified and auto-export discovery disabled; change at least one of these properties.");
        interfaces = new Class[0];
    }
    // check visibility type
    else {
        if (!ServiceFactory.class.isAssignableFrom(targetClass)) {
            for (int interfaceIndex = 0; interfaceIndex < interfaces.length; interfaceIndex++) {
                Class<?> intf = interfaces[interfaceIndex];
                Assert.isAssignable(intf, targetClass,
                        "Exported service object does not implement the given interface: ");
            }
        }
    }
    // check service properties listener
    if (serviceProperties instanceof ServicePropertiesListenerManager) {
        propertiesListener = new PropertiesMonitor();
        ((ServicePropertiesListenerManager) serviceProperties).addListener(propertiesListener);
    }

    boolean shouldRegisterAtStartup;
    synchronized (lock) {
        shouldRegisterAtStartup = registerAtStartup;
    }

    resolver = new LazyTargetResolver(target, beanFactory, targetBeanName, cacheTarget, getNotifier(),
            getLazyListeners());

    if (shouldRegisterAtStartup) {
        registerService();
    }
}

From source file:org.opentides.web.controller.ImageController.java

/**
 * Process image upload. /*from  w w  w.  j  av  a2 s. co  m*/
 * 
 * <p>
 * This method can automatically attach the image to an entity if the parameters className
 * and id were provided. The ImageUploadable class needs to have a service class implementing {@link BaseCrudService}
 * since it will search via convention the required service. 
 * <p>
 * 
 * <p>
 * This will return a map containing the list of MessageResponse objects. The MessageResponse will
 * contain error messages if there are validation problems or upload problems. Otherwise it
 * will just return a success message.
 * </p>
 * 
 * @param image
 * @param className the class name of the ImageUploadable entity. 
 * @param id the ID of the ImageUploadable entity
 * @param isPrimary if the image is the primary photo of the entity
 * @param result contains any validation errors
 * @param request
 * @return JSON format of a map containing the list of MessageResponse objects and the id of the ImageInfo. 
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(method = RequestMethod.POST, value = "/upload", produces = "application/json")
public @ResponseBody Map<String, Object> processUpload(@Valid @ModelAttribute("image") AjaxUpload image,
        @RequestParam(value = "className", required = false) String className,
        @RequestParam(value = "classId", required = false) Long id,
        @RequestParam(value = "isPrimary", required = false) boolean isPrimary,
        @RequestParam(value = "folderName", required = false) String folderName, BindingResult result,
        HttpServletRequest request) {

    BaseEntity entity = null;
    BaseCrudService service = null;
    if (!StringUtil.isEmpty(className) && id != null) {
        String attributeName = NamingUtil.toAttributeName(className);
        String serviceBean = attributeName + "Service";

        service = (BaseCrudService) beanFactory.getBean(serviceBean);
        Assert.notNull(service, "Entity " + attributeName + " is not associated with a service class ["
                + serviceBean + "]. Please check your configuration.");

        entity = service.load(id);
        Assert.notNull(entity, "No " + className + " object found for the given ID [" + id + "]");
        Assert.isAssignable(ImageUploadable.class, entity.getClass(), "Object is not ImageUploadable");
    }

    Map<String, Object> model = new HashMap<String, Object>();
    List<MessageResponse> messages = new ArrayList<MessageResponse>();

    if (result.hasErrors()) {
        messages.addAll(CrudUtil.convertErrorMessage(result, request.getLocale(), messageSource));
        model.put("messages", messages);
        return model;
    }

    FileInfo f = defaultFileUploadService.upload(image.getAttachment());

    ImageInfo imageInfo = new ImageInfo(f);
    imageInfo.setIsPrimary(isPrimary);
    imageInfoService.save(imageInfo);

    if (entity != null) {
        //Attach to entity
        ImageUploadable imageUploadable = (ImageUploadable) entity;
        if (isPrimary) {
            if (imageUploadable.getImages() != null) {
                for (ImageInfo io : imageUploadable.getImages()) {
                    io.setIsPrimary(false);
                    imageInfoService.save(io);
                }
            }
        }
        imageUploadable.addImage(imageInfo);
        service.save(entity);
    }

    messages.addAll(
            CrudUtil.buildSuccessMessage(imageInfo, "upload-photo", request.getLocale(), messageSource));
    model.put("messages", messages);
    model.put("attachmentId", imageInfo.getId());
    return model;
}

From source file:org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.java

private void verifyResultCollectionConsistsOfMessages(Collection<?> elements) {
    Class<?> commonElementType = CollectionUtils.findCommonElementType(elements);
    Assert.isAssignable(Message.class, commonElementType,
            "The expected collection of Messages contains non-Message element: " + commonElementType);
}

From source file:org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.java

public void setBeanFactory(BeanFactory beanFactory) {
    Assert.isAssignable(ConfigurableListableBeanFactory.class, beanFactory.getClass(),
            "a ConfigurableListableBeanFactory is required");
    this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}

From source file:org.springframework.statemachine.processor.StateMachineAnnotationPostProcessor.java

@Override
public void setBeanFactory(BeanFactory beanFactory) {
    Assert.isAssignable(ConfigurableListableBeanFactory.class, beanFactory.getClass(),
            "a ConfigurableListableBeanFactory is required");
    this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}

From source file:org.vaadin.spring.navigator.SpringViewProvider.java

private boolean isViewBeanNameValidForCurrentUI(String beanName) {
    try {//from   w w  w.j  a va2 s . co m
        Class<?> type = applicationContext.getType(beanName);

        Assert.isAssignable(View.class, type, "bean did not implement View interface");

        return isViewClassValidForCurrentUI((Class<? extends View>) type);
    } catch (NoSuchBeanDefinitionException ex) {
        return false;
    }
}