@Override public void afterPropertiesSet() throws Exception { if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) { throw new BeanInstantiationException(this.getClass(), "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties."); } if (logger.isDebugEnabled()) { CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration(); logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName()); config = this.ticketGrantingTicketsCache.getCacheConfiguration(); logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager() .getName()); } }
private List<TestExecutionListener> instantiateListeners(List<Class<? extends TestExecutionListener>> classesList) { List<TestExecutionListener> listeners = new ArrayList<TestExecutionListener>(classesList.size()); for (Class<? extends TestExecutionListener> listenerClass : classesList) { NoClassDefFoundError ncdfe = null; try { listeners.add(BeanUtils.instantiateClass(listenerClass)); } catch (NoClassDefFoundError err) { ncdfe = err; } catch (BeanInstantiationException ex) { if (ex.getCause() instanceof NoClassDefFoundError) { ncdfe = (NoClassDefFoundError) ex.getCause(); } } if (ncdfe != null) { if (logger.isInfoEnabled()) { logger.info(String.format("Could not instantiate TestExecutionListener [%s]. " + "Specify custom listener classes or make the default listener classes " + "(and their required dependencies) available. Offending class: [%s]", listenerClass.getName(), ncdfe.getMessage())); } } } return listeners; }
/** * Create a new instance of a dynamically generated subclass implementing the * required lookups. * @param ctor constructor to use. If this is {@code null}, use the * no-arg constructor (no parameterization, or Setter Injection) * @param args arguments to use for the constructor. * Ignored if the {@code ctor} parameter is {@code null}. * @return new instance of the dynamically generated subclass */ public Object instantiate(Constructor<?> ctor, Object... args) { Class<?> subclass = createEnhancedSubclass(this.beanDefinition); Object instance; if (ctor == null) { instance = BeanUtils.instantiate(subclass); } else { try { Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes()); instance = enhancedSubclassConstructor.newInstance(args); } catch (Exception ex) { throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex); } } // SPR-10785: set callbacks directly on the instance instead of in the // enhanced class (via the Enhancer) in order to avoid memory leaks. Factory factory = (Factory) instance; factory.setCallbacks(new Callback[] {NoOp.INSTANCE, new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner), new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)}); return instance; }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class targetClass = bean.getClass(); while(targetClass.getName().contains(CGLIB_SIGNATURE)) { for(Class interf: targetClass.getInterfaces()) { if(interf == TransactionalIntercepted.class) return bean; } targetClass = targetClass.getSuperclass(); } Method[] methods = targetClass.getDeclaredMethods(); for (Method method : methods) { Transactional txAnnotation = method.getAnnotation(Transactional.class); if (txAnnotation != null) { throw new BeanInstantiationException(targetClass, "Bean annotated by @Transactional must be created through DalTransactionManager.create()"); } } return bean; }
private static LBHttpSolrClient cloneLBHttpSolrClient(SolrClient solrClient, String core) { if (solrClient == null) { return null; } LBHttpSolrClient clone = null; try { if (VersionUtil.isSolr3XAvailable()) { clone = cloneSolr3LBHttpServer(solrClient, core); } else if (VersionUtil.isSolr4XAvailable()) { clone = cloneSolr4LBHttpServer(solrClient, core); } } catch (Exception e) { throw new BeanInstantiationException(solrClient.getClass(), "Cannot create instace of " + solrClient.getClass() + ". ", e); } Object o = readField(solrClient, "interval"); if (o != null) { clone.setAliveCheckInterval(Integer.valueOf(o.toString()).intValue()); } return clone; }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SimpleStorageResourceLoader simpleStorageResourceLoader = new SimpleStorageResourceLoader(this.amazonS3, this.resourceLoader); if (this.executor != null) { simpleStorageResourceLoader.setTaskExecutor(this.executor); } try { simpleStorageResourceLoader.afterPropertiesSet(); } catch (Exception e) { throw new BeanInstantiationException(SimpleStorageResourceLoader.class, "Error instantiating class", e); } this.resourceLoader = new PathMatchingSimpleStorageResourcePatternResolver(this.amazonS3, simpleStorageResourceLoader, (ResourcePatternResolver) this.resourceLoader); beanFactory.registerResolvableDependency(ResourceLoader.class, this.resourceLoader); }
private static LBHttpSolrServer cloneLBHttpSolrServer(SolrServer solrServer, String core) { if (solrServer == null) { return null; } LBHttpSolrServer clone = null; try { if (VersionUtil.isSolr3XAvailable()) { clone = cloneSolr3LBHttpServer(solrServer, core); } else if (VersionUtil.isSolr4XAvailable()) { clone = cloneSolr4LBHttpServer(solrServer, core); } } catch (MalformedURLException e) { throw new BeanInstantiationException(solrServer.getClass(), "Cannot create instace of " + solrServer.getClass() + ". ", e); } Object o = readField(solrServer, "interval"); if (o != null) { clone.setAliveCheckInterval(Integer.valueOf(o.toString()).intValue()); } return clone; }
@Override public void afterPropertiesSet() { logger.info("Setting up Ehcache Ticket Registry..."); if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) { throw new BeanInstantiationException(this.getClass(), "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties."); } if (logger.isDebugEnabled()) { CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration(); logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName()); config = this.ticketGrantingTicketsCache.getCacheConfiguration(); logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager() .getName()); } }
@Override public void afterPropertiesSet() throws Exception { logger.info("Setting up Ehcache Ticket Registry..."); if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) { throw new BeanInstantiationException(this.getClass(), "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties."); } if (logger.isDebugEnabled()) { CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration(); logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName()); config = this.ticketGrantingTicketsCache.getCacheConfiguration(); logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap()); logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk()); logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk()); logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds()); logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds()); logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager() .getName()); } }
@Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (beanDefinition.constructorArgumentLock) { constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() { @Override public Constructor<?> run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }
/** * Create a new instance of a dynamically generated subclass implementing the * required lookups. * @param ctor constructor to use. If this is {@code null}, use the * no-arg constructor (no parameterization, or Setter Injection) * @param args arguments to use for the constructor. * Ignored if the {@code ctor} parameter is {@code null}. * @return new instance of the dynamically generated subclass */ Object instantiate(Constructor<?> ctor, Object[] args) { Class<?> subclass = createEnhancedSubclass(this.beanDefinition); Object instance; if (ctor == null) { instance = BeanUtils.instantiate(subclass); } else { try { Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes()); instance = enhancedSubclassConstructor.newInstance(args); } catch (Exception e) { throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format( "Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e); } } // SPR-10785: set callbacks directly on the instance instead of in the // enhanced class (via the Enhancer) in order to avoid memory leaks. Factory factory = (Factory) instance; factory.setCallbacks(new Callback[] { NoOp.INSTANCE,// new LookupOverrideMethodInterceptor(beanDefinition, owner),// new ReplaceOverrideMethodInterceptor(beanDefinition, owner) }); return instance; }
@Test public void testProxyingDecoratorNoInstance() throws Exception { String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.class); assertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance")); assertEquals(ApplicationListener.class, this.beanFactory.getType("debuggingTestBeanNoInstance")); try { this.beanFactory.getBean("debuggingTestBeanNoInstance"); fail("Should have thrown BeanCreationException"); } catch (BeanCreationException ex) { assertTrue(ex.getRootCause() instanceof BeanInstantiationException); } }
@Test(expected=BeanInstantiationException.class) public void getHandlerNoBeanFactory() { BeanCreatingHandlerProvider<EchoHandler> provider = new BeanCreatingHandlerProvider<EchoHandler>(EchoHandler.class); provider.getHandler(); }
@Override public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (bd.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (bd.constructorArgumentLock) { constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = bd.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() { @Override public Constructor<?> run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } bd.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(bd, beanName, owner); } }
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // System.err.println("postProcessBeforeInitialization:" + beanName); Class<?> clazz = bean.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { Value annotation = field.getAnnotation(Value.class); if (annotation == null) { continue; } field.setAccessible(true); Object value = resolveValue(annotation, field); if (value == null) { continue; } try { field.set(bean, value); FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setBean(bean); fieldInfo.setField(field); fieldList.add(fieldInfo); } catch (IllegalAccessException e) { throw new BeanInstantiationException(clazz, e.getMessage(), e); } } return bean; }
private String getConsumerDescription(Throwable ex) { UnsatisfiedDependencyException unsatisfiedDependency = findUnsatisfiedDependencyException( ex); if (unsatisfiedDependency != null) { return getConsumerDescription(unsatisfiedDependency); } BeanInstantiationException beanInstantiationException = findBeanInstantiationException( ex); if (beanInstantiationException != null) { return getConsumerDescription(beanInstantiationException); } return null; }
private String getConsumerDescription(BeanInstantiationException ex) { if (ex.getConstructingMethod() != null) { return String.format("Method %s in %s", ex.getConstructingMethod().getName(), ex.getConstructingMethod().getDeclaringClass().getName()); } if (ex.getConstructor() != null) { return String.format("Constructor in %s", ClassUtils .getUserClass(ex.getConstructor().getDeclaringClass()).getName()); } return ex.getBeanClass().getName(); }
@Test public void whenDynamicModeAndMultipleServerListThenMemcachedNotLoaded() { thrown.expect(BeanCreationException.class); thrown.expectMessage("Only one configuration endpoint is valid with dynamic client mode."); thrown.expectCause(isA(BeanInstantiationException.class)); loadContext(CacheConfiguration.class, "memcached.cache.servers=192.168.99.100:11212, 192.168.99.101:11211", "memcached.cache.mode=dynamic"); }
@Test public void testValidateRawBean() throws Exception { DalAnnotationValidator test = new DalAnnotationValidator(); try{ TransactionAnnoClass bean = new TransactionAnnoClass(); test.postProcessAfterInitialization(bean, "beanName"); fail(); }catch(BeanInstantiationException e) { assertTrue(e.getMessage().contains("Bean annotated by @Transactional must be created through DalTransactionManager.create()")); } }
private static Object instantiateClass(Class<?> clazz) throws BeanInstantiationException { try { return clazz.newInstance(); } catch (Exception ex) { throw new BeanInstantiationException(clazz, ex.getMessage(), ex); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static SolrClient cloneEmbeddedSolrServer(SolrClient solrClient, String core) { CoreContainer coreContainer = ((EmbeddedSolrServer) solrClient).getCoreContainer(); try { Constructor constructor = ClassUtils.getConstructorIfAvailable(solrClient.getClass(), CoreContainer.class, String.class); return (SolrClient) BeanUtils.instantiateClass(constructor, coreContainer, core); } catch (Exception e) { throw new BeanInstantiationException(solrClient.getClass(), "Cannot create instace of " + solrClient.getClass() + ".", e); } }
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (beanDefinition.constructorArgumentLock) { constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() { public Constructor<?> run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static SolrServer cloneEmbeddedSolrServer(SolrServer solrServer, String core) { String solrHome = ((EmbeddedSolrServer) solrServer).getCoreContainer().getSolrHome(); try { Constructor constructor = ClassUtils.getConstructorIfAvailable(solrServer.getClass(), CoreContainer.class, String.class); return (SolrServer) BeanUtils.instantiateClass(constructor, new CoreContainer(solrHome), core); } catch (Exception e) { throw new BeanInstantiationException(solrServer.getClass(), "Cannot create instace of " + solrServer.getClass() + ".", e); } }
/** * {@inheritDoc} */ public Field createField(Item item, Object propertyId, Component uiContext) { Class<Field> clazz = fieldMap.get(propertyId); if (clazz != null) { try { return BeanUtils.instantiate(clazz); } catch(BeanInstantiationException bie) { log.error(bie); } } return null; }
private BeanInstantiationException findBeanInstantiationException(Throwable root) { return findMostNestedCause(root, BeanInstantiationException.class); }
private <T> TProcessor createTProcessor(Class<?> iFaceClass, Class<TProcessor> processorClass, T wrappedHandler) throws BeanInstantiationException, NoSuchMethodException, SecurityException { return BeanUtils.instantiateClass(processorClass.getConstructor(iFaceClass), wrappedHandler); }
@Override public CamelPostProcessorHelper getPostProcessorHelper() { // lets lazily create the post processor if (camelPostProcessorHelper == null) { camelPostProcessorHelper = new CamelPostProcessorHelper() { @Override public CamelContext getCamelContext() { // lets lazily lookup the camel context here // as doing this will cause this context to be started immediately // breaking the lifecycle ordering of different camel contexts // so we only want to do this on demand return delegate.getOrLookupCamelContext(); } @Override protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) { return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e); } protected boolean isSingleton(Object bean, String beanName) { // no application context has been injected which means the bean // has not been enlisted in Spring application context if (applicationContext == null || beanName == null) { return super.isSingleton(bean, beanName); } else { return applicationContext.isSingleton(beanName); } } protected void startService(Service service, Object bean, String beanName) throws Exception { if (isSingleton(bean, beanName)) { getCamelContext().addService(service); } else { // only start service and do not add it to CamelContext ServiceHelper.startService(service); if (prototypeBeans.add(beanName)) { // do not spam the log with WARN so do this only once per bean name CamelBeanPostProcessor.LOG.warn("The bean with id [" + beanName + "] is prototype scoped and cannot stop the injected service when bean is destroyed: " + service + ". You may want to stop the service manually from the bean."); } } } }; } return camelPostProcessorHelper; }