Java Code Examples for org.springframework.beans.factory.BeanCreationException

The following are top voted examples for showing how to use org.springframework.beans.factory.BeanCreationException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cas-5.1.0   File: SamlIdPConfiguration.java   View source code 8 votes vote down vote up
@Bean
public MetadataResolver casSamlIdPMetadataResolver() {
    try {
        final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
        final ResourceBackedMetadataResolver resolver = new ResourceBackedMetadataResolver(
                ResourceHelper.of(new FileSystemResource(idp.getMetadata().getMetadataFile())));
        resolver.setParserPool(this.openSamlConfigBean.getParserPool());
        resolver.setFailFastInitialization(idp.getMetadata().isFailFast());
        resolver.setRequireValidMetadata(idp.getMetadata().isRequireValidMetadata());
        resolver.setId(idp.getEntityId());
        resolver.initialize();
        return resolver;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 2
Project: cas-5.1.0   File: AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java   View source code 6 votes vote down vote up
@Bean
public PFAuth azureAuthenticatorInstance() {
    try {
        final MultifactorAuthenticationProperties.Azure azure = casProperties.getAuthn().getMfa().getAzure();
        final File cfg = new File(azure.getConfigDir());
        if (!cfg.exists() || !cfg.isDirectory()) {
            throw new FileNotFoundException(cfg.getAbsolutePath() + " does not exist or is not a directory");
        }
        final PFAuth pf = new PFAuth();
        pf.setDebug(true);
        pf.setAllowInternationalCalls(azure.isAllowInternationalCalls());

        final String dir = StringUtils.appendIfMissing(azure.getConfigDir(), "/");
        pf.initialize(dir, azure.getPrivateKeyPassword());
        return pf;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 3
Project: cas-5.1.0   File: DuoSecurityAuthenticationEventExecutionPlanConfiguration.java   View source code 6 votes vote down vote up
@RefreshScope
@Bean
public AuthenticationHandler duoAuthenticationHandler() {
    final DuoAuthenticationHandler h;
    final List<MultifactorAuthenticationProperties.Duo> duos = casProperties.getAuthn().getMfa().getDuo();
    if (!duos.isEmpty()) {
        final String name = duos.get(0).getName();
        if (duos.size() > 1) {
            LOGGER.debug("Multiple Duo Security providers are available; Duo authentication handler is named after [{}]", name);
        }
        h = new DuoAuthenticationHandler(name, servicesManager, duoPrincipalFactory(), duoMultifactorAuthenticationProvider());
    } else {
        h = new DuoAuthenticationHandler(StringUtils.EMPTY, servicesManager, duoPrincipalFactory(), duoMultifactorAuthenticationProvider());
        throw new BeanCreationException("No configuration/settings could be found for Duo Security. Review settings and ensure the correct syntax is used");
    }
    return h;
}
 
Example 4
Project: cas-5.1.0   File: GraphicalUserAuthenticationConfiguration.java   View source code 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "userGraphicalAuthenticationRepository")
public UserGraphicalAuthenticationRepository userGraphicalAuthenticationRepository() {

    final GraphicalUserAuthenticationProperties gua = casProperties.getAuthn().getGua();
    if (StringUtils.isNotBlank(gua.getResource().getLocation())) {
        return new StaticUserGraphicalAuthenticationRepository();
    }

    if (StringUtils.isNotBlank(gua.getLdap().getLdapUrl())
            && StringUtils.isNotBlank(gua.getLdap().getUserFilter())
            && StringUtils.isNotBlank(gua.getLdap().getBaseDn())
            && StringUtils.isNotBlank(gua.getLdap().getImageAttribute())) {
        return new LdapUserGraphicalAuthenticationRepository();
    }

    throw new BeanCreationException("A repository instance must be configured to locate user-defined graphics");

}
 
Example 5
Project: cas-5.1.0   File: SurrogateAuthenticationConfiguration.java   View source code 6 votes vote down vote up
@RefreshScope
@ConditionalOnMissingBean(name = "surrogateAuthenticationService")
@Bean
public SurrogateAuthenticationService surrogateAuthenticationService() {
    try {
        final SurrogateAuthenticationProperties su = casProperties.getAuthn().getSurrogate();
        if (su.getJson().getConfig().getLocation() != null) {
            LOGGER.debug("Using JSON resource [{}] to locate surrogate accounts", su.getJson().getConfig().getLocation());
            return new JsonResourceSurrogateAuthenticationService(su.getJson().getConfig().getLocation());
        }
        if (StringUtils.hasText(su.getLdap().getLdapUrl()) && StringUtils.hasText(su.getLdap().getSearchFilter())
                && StringUtils.hasText(su.getLdap().getBaseDn()) && StringUtils.hasText(su.getLdap().getMemberAttributeName())) {
            LOGGER.debug("Using LDAP [{}] with baseDn [{}] to locate surrogate accounts",
                    su.getLdap().getLdapUrl(), su.getLdap().getBaseDn());
            final ConnectionFactory factory = Beans.newLdaptivePooledConnectionFactory(su.getLdap());
            return new LdapSurrogateUsernamePasswordService(factory, su.getLdap());
        }

        final Map<String, Set> accounts = new LinkedHashMap<>();
        su.getSimple().getSurrogates().forEach((k, v) -> accounts.put(k, StringUtils.commaDelimitedListToSet(v)));
        LOGGER.debug("Using accounts [{}] for surrogate authentication", accounts);
        return new SimpleSurrogateAuthenticationService(accounts);
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 6
Project: composed-task-runner   File: ComposedRunnerVisitorTests.java   View source code 6 votes vote down vote up
@Test
public void failedStepTransitionWithDuplicateTaskNameTest() {
	try {
		setupContextForGraph("failedStep 'FAILED' -> BBB  && CCC && BBB && EEE");
	}
	catch (BeanCreationException bce) {
		assertEquals(TaskValidationException.class,
				bce.getRootCause().getClass());
		assertEquals("Problems found when validating 'failedStep " +
						"'FAILED' -> BBB  && CCC && BBB && EEE': " +
						"[166E:(pos 38): duplicate app name. Use a " +
						"label to ensure uniqueness]",
				bce.getRootCause().getMessage());
	}

}
 
Example 7
Project: composed-task-runner   File: ComposedRunnerVisitorTests.java   View source code 6 votes vote down vote up
@Test
public void successStepTransitionWithDuplicateTaskNameTest() {
	try {
		setupContextForGraph("AAA 'FAILED' -> BBB  * -> CCC && BBB && EEE");
	}
	catch (BeanCreationException bce) {
		assertEquals(TaskValidationException.class,
				bce.getRootCause().getClass());
		assertEquals("Problems found when validating 'AAA 'FAILED' -> " +
						"BBB  * -> CCC && BBB && EEE': [166E:(pos 33): " +
						"duplicate app name. Use a label to ensure " +
						"uniqueness]",
				bce.getRootCause().getMessage());
	}

}
 
Example 8
Project: lams   File: AbstractAutowireCapableBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
		throws BeansException {

	try {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}
	catch (Exception ex) {
		throw new BeanCreationException(mbd.getResourceDescription(), beanName,
				"Post-processing failed of bean type [" + beanType + "] failed", ex);
	}
}
 
Example 9
Project: lams   File: AbstractBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		// Can only happen when getting a FactoryBean.
		if (logger.isDebugEnabled()) {
			logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex);
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example 10
Project: circus-train   File: VacuumTool.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(VacuumTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printVacuumToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
 
Example 11
Project: circus-train   File: FilterTool.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(FilterTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printFilterToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
 
Example 12
Project: lams   File: BeanDefinitionValueResolver.java   View source code 6 votes vote down vote up
/**
 * Resolve a reference to another bean in the factory.
 */
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
	try {
		String refName = ref.getBeanName();
		refName = String.valueOf(evaluate(refName));
		if (ref.isToParent()) {
			if (this.beanFactory.getParentBeanFactory() == null) {
				throw new BeanCreationException(
						this.beanDefinition.getResourceDescription(), this.beanName,
						"Can't resolve reference to bean '" + refName +
						"' in parent factory: no parent factory available");
			}
			return this.beanFactory.getParentBeanFactory().getBean(refName);
		}
		else {
			Object bean = this.beanFactory.getBean(refName);
			this.beanFactory.registerDependentBean(refName, this.beanName);
			return bean;
		}
	}
	catch (BeansException ex) {
		throw new BeanCreationException(
				this.beanDefinition.getResourceDescription(), this.beanName,
				"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
	}
}
 
Example 13
Project: azure-spring-boot   File: MediaServicesAutoConfigurationTest.java   View source code 6 votes vote down vote up
private void createAndFailWithCause(String cause) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(MediaServicesAutoConfiguration.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getCause().toString()).contains(cause);
    }
}
 
Example 14
Project: azure-spring-boot   File: DocumentDBPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void emptySettingNotAllowed() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.documentdb' on field 'uri': rejected value [null];");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.documentdb' on field 'key': rejected value [null];");
    }
}
 
Example 15
Project: azure-spring-boot   File: ServiceBusPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void connectionStringIsNull() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.servicebus' on field 'connectionString': "
                        + "rejected value [null];");
    }
}
 
Example 16
Project: azure-spring-boot   File: ServiceBusAutoConfigurationTest.java   View source code 6 votes vote down vote up
private void verifyBeanCreationException(String message, Class<?> beanClass) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        Exception exception = null;
        try {
            context.register(ServiceBusAutoConfiguration.class);
            context.refresh();
            context.getBean(beanClass);
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception.getMessage()).contains(message);
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
    }
}
 
Example 17
Project: azure-spring-boot   File: StorageAutoConfigurationTest.java   View source code 6 votes vote down vote up
@Test
public void createStorageAccountWithInvalidConnectionString() {
    System.setProperty(CONNECTION_STRING_PROPERTY, INVALID_CONNECTION_STRING);

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(StorageAutoConfiguration.class);
        context.refresh();

        CloudStorageAccount cloudStorageAccount = null;
        try {
            cloudStorageAccount = context.getBean(CloudStorageAccount.class);
        } catch (Exception e) {
            assertThat(e).isExactlyInstanceOf(BeanCreationException.class);
        }

        assertThat(cloudStorageAccount).isNull();
    }

    System.clearProperty(CONNECTION_STRING_PROPERTY);
}
 
Example 18
Project: lams   File: AbstractAutowireCapableBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
	try {
		Object beanInstance;
		final BeanFactory parent = this;
		if (System.getSecurityManager() != null) {
			beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					return getInstantiationStrategy().instantiate(mbd, beanName, parent);
				}
			}, getAccessControlContext());
		}
		else {
			beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
		}
		BeanWrapper bw = new BeanWrapperImpl(beanInstance);
		initBeanWrapper(bw);
		return bw;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
	}
}
 
Example 19
Project: shibboleth-idp-oidc-extension   File: BasicJWKCredentialFactoryBean.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected BasicJWKCredential doCreateInstance() throws Exception {

    if (jwkResource == null) {
        log.error("{}: No JWK credential provided", getConfigDescription());
        throw new BeanCreationException("No JWK credential provided");
    }
    JWK jwk = null;
    BasicJWKCredential jwkCredential = null;
    try (InputStream is = jwkResource.getInputStream()) {
        jwk = JWK.parse(new String(ByteStreams.toByteArray(is)));
        jwkCredential = new BasicJWKCredential();
        if (jwk.getKeyType() == KeyType.EC || jwk.getKeyType() == KeyType.RSA) {
            if (jwk.isPrivate()) {
                jwkCredential.setPrivateKey(((AssymetricJWK) jwk).toPrivateKey());
            }
            jwkCredential.setPublicKey(((AssymetricJWK) jwk).toPublicKey());
        } else if (jwk.getKeyType() == KeyType.OCT) {
            jwkCredential.setSecretKey(((OctetSequenceKey) jwk).toSecretKey());
        } else {
            throw new FatalBeanException("Unsupported KeyFile at " + jwkResource.getDescription());
        }
    } catch (IOException | ParseException | JOSEException e) {
        log.error("{}: Could not decode KeyFile at {}: {}", 
                getConfigDescription(), jwkResource.getDescription(), e);
        throw new FatalBeanException("Could not decode provided KeyFile " + jwkResource.getDescription(), e);
    }
    jwkCredential.setUsageType(getUsageType(jwk));
    jwkCredential.setEntityId(getEntityID());
    jwkCredential.setAlgorithm(jwk.getAlgorithm());
    jwkCredential.setKid(jwk.getKeyID());
    final List<String> keyNames = getKeyNames();
    if (keyNames != null) {
        jwkCredential.getKeyNames().addAll(keyNames);
    }
    return jwkCredential;
}
 
Example 20
Project: dubbox-hystrix   File: ConfigTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
 
Example 21
Project: oasp-tutorial-sources   File: BeansBatchConfig.java   View source code 5 votes vote down vote up
/**
 * This method is creating jobLauncher bean
 *
 * @return SimpleJobLauncher
 */
@Bean
@DependsOn("jobRepository")
public JobLauncherWithAdditionalRestartCapabilities jobLauncher() {

  this.jobLauncher = new JobLauncherWithAdditionalRestartCapabilities();

  try {
    this.jobLauncher.setJobRepository(this.jobRepository.getObject());
  } catch (Exception e) {
    throw new BeanCreationException("Could not create BatchJobOperator", e);
  }

  return this.jobLauncher;
}
 
Example 22
Project: lams   File: StaticListableBeanFactory.java   View source code 5 votes vote down vote up
@Override
public Object getBean(String name) throws BeansException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);
	Object bean = this.beans.get(beanName);

	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	// Don't let calling code try to dereference the
	// bean factory if the bean isn't a factory
	if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) {
		throw new BeanIsNotAFactoryException(beanName, bean.getClass());
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		try {
			return ((FactoryBean<?>) bean).getObject();
		}
		catch (Exception ex) {
			throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
		}
	}
	else {
		return bean;
	}
}
 
Example 23
Project: cas-5.1.0   File: CoreWsSecuritySecurityTokenServiceConfiguration.java   View source code 5 votes vote down vote up
@RefreshScope
@Bean
public Provider transportSTSProviderBean() {
    try {
        final SecurityTokenServiceProvider provider = new SecurityTokenServiceProvider();
        provider.setIssueOperation(transportIssueDelegate());
        provider.setValidateOperation(transportValidateDelegate());
        return provider;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 24
Project: cas-5.1.0   File: MongoDbCloudConfigBootstrapConfiguration.java   View source code 5 votes vote down vote up
@Bean
public MongoClientOptions mongoClientOptions() {
    try {
        final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
        bean.setSocketTimeout(TIMEOUT);
        bean.setConnectTimeout(TIMEOUT);
        bean.afterPropertiesSet();
        return bean.getObject();
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 25
Project: lams   File: PersistenceAnnotationBeanPostProcessor.java   View source code 5 votes vote down vote up
@Override
public PropertyValues postProcessPropertyValues(
		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

	InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass());
	try {
		metadata.inject(bean, beanName, pvs);
	}
	catch (Throwable ex) {
		throw new BeanCreationException(beanName, "Injection of persistence dependencies failed", ex);
	}
	return pvs;
}
 
Example 26
Project: composed-task-runner   File: ComposedRunnerVisitorTests.java   View source code 5 votes vote down vote up
@Test
public void testSequentialTransitionAndSplitFailedInvalid() {
	try {
		setupContextForGraph("AAA && failedStep 'FAILED' -> EEE '*' -> FFF && <BBB||CCC> && DDD");
	}
	catch (BeanCreationException bce) {
		validateInvalidFlowWildCard(bce);
	}
}
 
Example 27
Project: composed-task-runner   File: ComposedRunnerVisitorTests.java   View source code 5 votes vote down vote up
@Test
public void testSuccessBasicTransitionWithSequence() {
	try {
		setupContextForGraph("AAA 'FAILED' -> BBB * -> CCC && DDD && EEE");
	}
	catch (BeanCreationException bce) {
		validateInvalidFlowWildCard(bce);
	}
}
 
Example 28
Project: apollo-custom   File: JavaConfigAnnotationTest.java   View source code 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void testApolloConfigChangeListenerWithWrongParamType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean(TestApolloConfigChangeListenerBean2.class, AppConfig4.class);
}
 
Example 29
Project: dubbocloud   File: ConfigTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
 
Example 30
Project: zipkin-sparkstreaming   File: ZipkinStorageConsumerAutoConfigurationTest.java   View source code 5 votes vote down vote up
/** fail fast is default, which helps discover storage errors before the job runs */
@Test public void failFast() {
  addEnvironment(context,
      "zipkin.storage.type:elasticsearch",
      "zipkin.storage.elasticsearch.hosts:http://host1:9200"
  );
  context.register(PropertyPlaceholderAutoConfiguration.class,
      ZipkinStorageConsumerAutoConfiguration.class);

  thrown.expect(BeanCreationException.class);
  context.refresh();
}
 
Example 31
Project: spring-cloud-vault-connector   File: AbstractCloudConfigServiceTest.java   View source code 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void cloudConnectorWithoutServiceNameSpecified_TwoServiceExist_byId() {
	ApplicationContext testContext = getTestApplicationContextWithoutServiceId(
			createService("my-service"), createService("my-service-2"));

	testContext.getBean(getConnectorType());
}
 
Example 32
Project: EatDubbo   File: ConfigTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
 
Example 33
Project: cfsummiteu2017   File: PlatformRepositoryImpl.java   View source code 5 votes vote down vote up
@Override
public void addPlatform(Platform platform, PlatformService platformService) {
	if (platformServices.get(platform) == null)
		platformServices.put(platform, platformService);
	else
		throw new BeanCreationException("Cannot add multiple instances of platform service to PlatformRepository");
}
 
Example 34
Project: gemini.blueprint   File: ManagedServiceFactoryFactoryBean.java   View source code 5 votes vote down vote up
private void registerService(String pid, Object bean) {
	OsgiServiceFactoryBean exporter = createExporter(pid, bean);
	serviceExporters.put(pid, exporter);
	try {
		serviceRegistrations.add(exporter.getObject());
	} catch (Exception ex) {
		throw new BeanCreationException("Cannot publish bean for pid " + pid, ex);
	}
}
 
Example 35
Project: dubbo2   File: ConfigTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
 
Example 36
Project: gemini.blueprint   File: ManagedServiceFactoryFactoryBean.java   View source code 5 votes vote down vote up
private OsgiServiceFactoryBean createExporter(String beanName, Object bean) {
	OsgiServiceFactoryBean exporter = new OsgiServiceFactoryBean();
	exporter.setInterfaceDetector(detector);
	exporter.setBeanClassLoader(classLoader);
	exporter.setBeanName(beanName);
	exporter.setBundleContext(bundleContext);
	exporter.setExportContextClassLoader(ccl);
	exporter.setInterfaces(interfaces);
	exporter.setListeners(listeners);
	exporter.setTarget(bean);

	// add properties
	Properties props = new Properties();
	if (serviceProperties != null) {
		props.putAll(serviceProperties);
	}
	// add the service pid (to be able to identify the bean instance)
	props.put(Constants.SERVICE_PID, beanName);
	exporter.setServiceProperties(props);

	try {
		exporter.afterPropertiesSet();
	} catch (Exception ex) {
		throw new BeanCreationException("Cannot publish bean for pid " + beanName, ex);
	}
	return exporter;
}
 
Example 37
Project: apollo-custom   File: XMLConfigAnnotationTest.java   View source code 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void testApolloConfigWithWrongFieldType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean("spring/XmlConfigAnnotationTest2.xml", TestApolloConfigBean2.class);
}
 
Example 38
Project: lams   File: AutowiredAnnotationBeanPostProcessor.java   View source code 5 votes vote down vote up
/**
 * 'Native' processing method for direct calls with an arbitrary target instance,
 * resolving all of its fields and methods which are annotated with {@code @Autowired}.
 * @param bean the target instance to process
 * @throws BeansException if autowiring failed
 */
public void processInjection(Object bean) throws BeansException {
	Class<?> clazz = bean.getClass();
	InjectionMetadata metadata = findAutowiringMetadata(clazz.getName(), clazz);
	try {
		metadata.inject(bean, null, null);
	}
	catch (Throwable ex) {
		throw new BeanCreationException("Injection of autowired dependencies failed for class [" + clazz + "]", ex);
	}
}
 
Example 39
Project: apollo-custom   File: JavaConfigAnnotationTest.java   View source code 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void testApolloConfigWithWrongFieldType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean(TestApolloConfigBean2.class, AppConfig2.class);
}
 
Example 40
Project: azure-spring-boot   File: AADAuthenticationFilterPropertiesTest.java   View source code 5 votes vote down vote up
@Test
public void emptySettingsNotAllowed() {
    System.setProperty(Constants.CLIENT_ID_PROPERTY, "");
    System.setProperty(Constants.CLIENT_SECRET_PROPERTY, "");

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientId': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientSecret': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'activeDirectoryGroups': rejected value [null]");
    }

    System.clearProperty(Constants.CLIENT_ID_PROPERTY);
    System.clearProperty(Constants.CLIENT_SECRET_PROPERTY);
}