private DataSource getDataSource(ApplicationContext applicationContext, Persistence persistenceSettings) { DataSource dataSource = null; Map<String, DataSource> datasources = applicationContext.getBeansOfType(DataSource.class); int dsSize = null != datasources ? datasources.size() : 0; if (null != datasources && null != persistenceSettings.getDataSourceName()) { dataSource = datasources.get(persistenceSettings.getDataSourceName()); } else if (null != datasources && dsSize == 1 && null == persistenceSettings.getDataSourceName()){ dataSource = datasources.values().iterator().next(); } if (dataSource == null) { throw new BeanInitializationException( "A datasource is required when starting Quartz-Scheduler in persisted mode. " + "No DS found in map with size: " + dsSize + ", and configured DSName: " + persistenceSettings.getDataSourceName()); } return dataSource; }
@Override protected AbstractShiroFilter createInstance() throws Exception { SecurityManager securityManager = getSecurityManager(); if (securityManager == null){ throw new BeanInitializationException("SecurityManager property must be set."); } if (!(securityManager instanceof WebSecurityManager)){ throw new BeanInitializationException("The security manager does not implement the WebSecurityManager interface."); } PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver(); FilterChainManager chainManager = createFilterChainManager(); chainResolver.setFilterChainManager(chainManager); return new MySpringShiroFilter((WebSecurityManager)securityManager, chainResolver); }
@Bean public Region awsRegion() { Region region; if(regionString != null && !regionString.isEmpty()) { region = RegionUtils.getRegion(regionString); } else { AwsRegionProvider regionProvider = new DefaultAwsRegionProviderChain(); region = RegionUtils.getRegion(regionProvider.getRegion()); } if(region == null) { throw new BeanInitializationException("Unable to determine AWS region"); } return region; }
private void createProperties() { if (properties == null) { properties = (dynamic ? new ChangeableProperties() : new Properties()); // init properties by copying config admin properties try { PropertiesUtil.initProperties(localProperties, localOverride, CMUtils.getConfiguration(bundleContext, persistentId, initTimeout), properties); } catch (IOException ioe) { throw new BeanInitializationException("Cannot retrieve configuration for pid=" + persistentId, ioe); } if (dynamic) { // perform eager registration registration = CMUtils.registerManagedService(bundleContext, new ConfigurationWatcher(), persistentId); } } }
@Override public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { if (!this.validatedBeanNames.contains(beanName)) { if (!shouldSkip(this.beanFactory, beanName)) { List<String> invalidProperties = new ArrayList<String>(); for (PropertyDescriptor pd : pds) { if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) { invalidProperties.add(pd.getName()); } } if (!invalidProperties.isEmpty()) { throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName)); } } this.validatedBeanNames.add(beanName); } return pvs; }
/** * {@linkplain #mergeProperties Merge}, {@linkplain #convertProperties convert} and * {@linkplain #processProperties process} properties against the given bean factory. * @throws BeanInitializationException if any properties cannot be loaded */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { try { Properties mergedProps = mergeProperties(); // Convert the merged properties, if necessary. convertProperties(mergedProps); // Let the subclass process the properties. processProperties(beanFactory, mergedProps); } catch (IOException ex) { throw new BeanInitializationException("Could not load properties", ex); } }
@Override protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException { for (Enumeration<?> names = props.propertyNames(); names.hasMoreElements();) { String key = (String) names.nextElement(); try { processKey(beanFactory, key, props.getProperty(key)); } catch (BeansException ex) { String msg = "Could not process key '" + key + "' in PropertyOverrideConfigurer"; if (!this.ignoreInvalidKeys) { throw new BeanInitializationException(msg, ex); } if (logger.isDebugEnabled()) { logger.debug(msg, ex); } } } }
/** * Process the given key as 'beanName.property' entry. */ protected void processKey(ConfigurableListableBeanFactory factory, String key, String value) throws BeansException { int separatorIndex = key.indexOf(this.beanNameSeparator); if (separatorIndex == -1) { throw new BeanInitializationException("Invalid key '" + key + "': expected 'beanName" + this.beanNameSeparator + "property'"); } String beanName = key.substring(0, separatorIndex); String beanProperty = key.substring(separatorIndex+1); this.beanNames.add(beanName); applyPropertyValue(factory, beanName, beanProperty, value); if (logger.isDebugEnabled()) { logger.debug("Property '" + key + "' set to value [" + value + "]"); } }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanNames = beanFactory.getBeanNamesForAnnotation(Job.class); for(String name : beanNames){ JobDetail jobDetail = buildJobForBeanFactory(beanFactory, name); if (jobDetail == null){ logger.warn("could not load JobDetail for {}", name); continue; } try { scheduler.addJob(jobDetail, true); } catch (SchedulerException e) { throw new BeanInitializationException("SchedulerException when adding job to scheduler", e); } } }
@Bean @ConditionalOnMissingBean public SamzaContainer samzaContainer() { JobModel jobModel = samzaJobModel(); int containerId = samzaContainerId(); Assert.isTrue(containerId >= 0, "samzaContainerId must be a non-negative integer (0 or greater)."); Map<Integer, ContainerModel> containers = jobModel.getContainers(); ContainerModel containerModel = containers.get(containerId); if (containerModel == null) { String msg = "Container model does not exist for samza container id '" + containerId + "'. " + "Ensure that samzaContainerId is a zero-based integer less than the total number " + "of containers for the job. Number of containers in the model: " + containers.size(); throw new BeanInitializationException(msg); } return SamzaContainer$.MODULE$.apply(containerModel, jobModel); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Portlet) { PortletConfig config = this.portletConfig; if (config == null || !this.useSharedPortletConfig) { config = new DelegatingPortletConfig(beanName, this.portletContext, this.portletConfig); } try { ((Portlet) bean).init(config); } catch (PortletException ex) { throw new BeanInitializationException("Portlet.init threw exception", ex); } } return bean; }
/** * Invoked on startup. Looks for a single FreeMarkerConfig bean to * find the relevant Configuration for this factory. * <p>Checks that the template for the default Locale can be found: * FreeMarker will check non-Locale-specific templates if a * locale-specific one is not found. * @see freemarker.cache.TemplateCache#getTemplate */ @Override protected void initServletContext(ServletContext servletContext) throws BeansException { if (getConfiguration() != null) { this.taglibFactory = new TaglibFactory(servletContext); } else { FreeMarkerConfig config = autodetectConfiguration(); setConfiguration(config.getConfiguration()); this.taglibFactory = config.getTaglibFactory(); } GenericServlet servlet = new GenericServletAdapter(); try { servlet.init(new DelegatingServletConfig()); } catch (ServletException ex) { throw new BeanInitializationException("Initialization of GenericServlet adapter failed", ex); } this.servletContextHashModel = new ServletContextHashModel(servlet, getObjectWrapper()); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Servlet) { ServletConfig config = this.servletConfig; if (config == null || !this.useSharedServletConfig) { config = new DelegatingServletConfig(beanName, this.servletContext); } try { ((Servlet) bean).init(config); } catch (ServletException ex) { throw new BeanInitializationException("Servlet.init threw exception", ex); } } return bean; }
/** * Return a {@link ContentNegotiationManager} instance to use to determine * requested {@linkplain MediaType media types} in a given request. */ @Bean public ContentNegotiationManager mvcContentNegotiationManager() { if (this.contentNegotiationManager == null) { ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(this.servletContext); configurer.mediaTypes(getDefaultMediaTypes()); configureContentNegotiation(configurer); try { this.contentNegotiationManager = configurer.getContentNegotiationManager(); } catch (Exception ex) { throw new BeanInitializationException("Could not create ContentNegotiationManager", ex); } } return this.contentNegotiationManager; }
/** * Create and start a new container using the specified factory. */ protected MessageListenerContainer createListenerContainer(JmsListenerEndpoint endpoint, JmsListenerContainerFactory<?> factory) { MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint); if (listenerContainer instanceof InitializingBean) { try { ((InitializingBean) listenerContainer).afterPropertiesSet(); } catch (Exception ex) { throw new BeanInitializationException("Failed to initialize message listener container", ex); } } int containerPhase = listenerContainer.getPhase(); if (containerPhase < Integer.MAX_VALUE) { // a custom phase value if (this.phase < Integer.MAX_VALUE && this.phase != containerPhase) { throw new IllegalStateException("Encountered phase mismatch between container factory definitions: " + this.phase + " vs " + containerPhase); } this.phase = listenerContainer.getPhase(); } return listenerContainer; }
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (inited) return; try { Properties mergedProps = mergeProperties(); // Convert the merged properties, if necessary. convertProperties(mergedProps); // Let the subclass process the properties. processProperties(beanFactory, mergedProps); inited = true; } catch (IOException ex) { throw new BeanInitializationException("Could not load properties", ex); } }
/** * Druid数据源配置 * * @return */ public DruidDataSource getDruidDataSource() { DruidDataSource dataSource = new DruidDataSource(); try { dataSource.setUsername(this.getUserName()); dataSource.setPassword(this.getPassword()); dataSource.setFilters(this.getFilters()); dataSource.setMaxActive(this.getMaxActive()); dataSource.setMinIdle(this.getMinIdle()); dataSource.setInitialSize(this.getInitialSize()); dataSource.setMaxWait(this.getMaxWait()); dataSource.setTimeBetweenEvictionRunsMillis(this.getTimeBetweenEvictionRunsMillis()); dataSource.setMinEvictableIdleTimeMillis(this.getMinEvictableIdleTimeMillis()); dataSource.setValidationQuery(this.getValidationQuery()); dataSource.setTestWhileIdle(this.getTestWhileIdle()); dataSource.setTestOnBorrow(this.getTestOnBorrow()); dataSource.setTestOnReturn(this.getTestOnReturn()); dataSource.setPoolPreparedStatements(this.getPoolPreparedStatements()); dataSource.setMaxPoolPreparedStatementPerConnectionSize(this.getMaxOpenPreparedStatements()); } catch (SQLException ex) { throw new BeanInitializationException("DataSouce初始化失败", ex); } return dataSource; }
@SuppressWarnings({"rawtypes"}) private Object inferReference(Reference reference, Class<?> referenceClazz) { String interfaceName; if (!"".equals(reference.interfaceName())) { interfaceName = reference.interfaceName(); } else if (!void.class.equals(reference.interfaceClass())) { interfaceName = reference.interfaceClass().getName(); } else if (referenceClazz.isInterface()) { interfaceName = referenceClazz.getName(); } else { //here we support to get the bean by the concrete class type interfaceName = referenceClazz.getName(); } RpcReference<?> rpcReference = new RpcReference(interfaceName, reference.preferredZone(), reference.usedTls(), reference.timeout()); try { return rpcReference.getObject(); } catch (Exception e) { throw new BeanInitializationException("Get object error happened.", e); } }
@PostConstruct private void init() { log.info("[JAR Loader::init] Registering file change listeners on root dir- "+root); try { watcher = root.getFileSystem().newWatchService(); } catch (Exception e) { throw new BeanInitializationException("Unable to register file watcher", e); } setInitialFiles(walkDirectory(root)); for(File f : getInitialFiles()) { loadDynamicLibrary(f); } new Thread(this, "DynamicModuleLoader.Worker").start(); log.info("[JAR Loader::init] Loaded dynamic modules on startup.."); }
private Application createApplication() { Energy4Java polygene = new Energy4Java(); try { return polygene.newApplication( factory -> { ApplicationAssembly applicationAssembly = factory.newApplicationAssembly(); applicationBootstrap.assemble( applicationAssembly ); return applicationAssembly; } ); } catch ( AssemblyException e ) { throw new BeanInitializationException( "Fail to bootstrap Polygene application.", e ); } }
@Bean @Lazy public Server hsqlServer() { Path path = Paths.get(env.getProperty("java.io.tmpdir"), "hsql", "wte4j"); String pathAsString = path.toAbsolutePath().toString(); logger.info("dblocation: {}", pathAsString); HsqlProperties p = new HsqlProperties(); p.setProperty("server.database.0", "file:" + pathAsString); p.setProperty("server.dbname.0", "wte4j"); try { Server server = new Server(); server.setProperties(p); return server; } catch (Exception e) { throw new BeanInitializationException("can not creat hsql server bean", e); } }
public void afterPropertiesSet() throws Exception { if ((incomingQueue == null) || (incomingQueue.equals(""))) { throw new BeanInitializationException("You must set a value for incomingQueue"); } if ((outgoingQueue == null) || (outgoingQueue.equals(""))) { throw new BeanInitializationException("You must set a value for outgoingQueue"); } logger.debug("Setting sourceUri to " + incomingQueue); logger.debug("Setting outgoingUri to " + outgoingQueue); sourceUri = "wmq:queue:" + incomingQueue; targetUri = "wmq:queue:" + outgoingQueue; }
/** * Initialize FreeMarker elements after servlet context and FreeMarker configuration have both * been populated. */ private static void finishConfig() { if (freeMarkerConfig != null && servletContext != null) { taglibFactory = new TaglibFactory(servletContext); objectWrapper = freeMarkerConfig.getObjectWrapper(); if (objectWrapper == null) { objectWrapper = ObjectWrapper.DEFAULT_WRAPPER; } GenericServlet servlet = new ServletAdapter(); try { servlet.init(new DelegatingServletConfig()); } catch (ServletException ex) { throw new BeanInitializationException("Initialization of GenericServlet adapter failed", ex); } servletContextHashModel = new ServletContextHashModel(servlet, ObjectWrapper.DEFAULT_WRAPPER); LOG.info("Freemarker configuration complete"); } }
protected final void registerHandlerMethodOnListenedChannel(Method method, StreamListener streamListener, Object bean) { Assert.hasText(streamListener.value(), "The binding name cannot be null"); if (!StringUtils.hasText(streamListener.value())) { throw new BeanInitializationException("A bound component name must be specified"); } final String defaultOutputChannel = StreamListenerMethodUtils.getOutboundBindingTargetName(method); if (Void.TYPE.equals(method.getReturnType())) { Assert.isTrue(StringUtils.isEmpty(defaultOutputChannel), "An output channel cannot be specified for a method that does not return a value"); } else { Assert.isTrue(!StringUtils.isEmpty(defaultOutputChannel), "An output channel must be specified for a method that can return a value"); } StreamListenerMethodUtils.validateStreamListenerMessageHandler(method); mappedListenerMethods.add(streamListener.value(), new StreamListenerHandlerMethodMapping(bean, method, streamListener.condition(), defaultOutputChannel, streamListener.copyHeaders())); }
public void afterPropertiesSet() throws Exception { if (!(beanFactory instanceof ListableBeanFactory)) throw new BeanInitializationException( "The workflow processor [" + beanName + "] " + "is not managed by a ListableBeanFactory, please re-deploy using some dirivative of ListableBeanFactory such as" + "ClassPathXmlApplicationContext "); if (activities == null || activities.isEmpty()) throw new UnsatisfiedDependencyException(getBeanDesc(), beanName, "activities", "No activities were wired for this workflow"); for (Iterator iter = activities.iterator(); iter.hasNext();) { Command activitiy = (Command) iter.next(); if (!supports(activitiy)) throw new BeanInitializationException("The workflow processor [" + beanName + "] does " + "not support the activity of type" + activitiy.getClass().getName()); } }
@Test public void testPropertyPlaceholderConfigurerWithSystemPropertyInLocation() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("spouse", new RuntimeBeanReference("${ref}")); ac.registerSingleton("tb", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("location", "${user.dir}/test"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanInitializationException"); } catch (BeanInitializationException ex) { // expected assertTrue(ex.getCause() instanceof FileNotFoundException); // slight hack for Linux/Unix systems String userDir = StringUtils.cleanPath(System.getProperty("user.dir")); if (userDir.startsWith("/")) { userDir = userDir.substring(1); } assertTrue(ex.getMessage().indexOf(userDir) != -1); } }
@Test public void testPropertyPlaceholderConfigurerWithUnresolvableSystemPropertiesInLocation() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("spouse", new RuntimeBeanReference("${ref}")); ac.registerSingleton("tb", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("location", "${myprop}/test/${myprop}"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanInitializationException"); } catch (BeanInitializationException ex) { // expected assertTrue(ex.getMessage().contains("myprop")); } }