Java Examples for org.springframework.beans.factory.annotation.Autowired
The following java examples will help you to understand the usage of org.springframework.beans.factory.annotation.Autowired. These source code samples are taken from different open source projects.
Example 1
| Project: ws-proxy-master File: PropertySources.java View source code |
@Bean
@Autowired
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ApplicationContext applicationContext) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setLocation(new FileSystemResource(applicationContext.getEnvironment().getProperty("project.root.dir") + "/config/wsproxy-local-config/wsproxy_local_demo.properties"));
return propertySourcesPlaceholderConfigurer;
}Example 2
| Project: apollo-master File: TestWebSecurityConfig.java View source code |
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("").roles("USER");
auth.inMemoryAuthentication().withUser("apollo").password("").roles("USER", "ADMIN");
auth.inMemoryAuthentication().withUser("created").password("").roles("TEST");
auth.inMemoryAuthentication().withUser("updated").password("").roles("TEST");
auth.inMemoryAuthentication().withUser("deleted").password("").roles("TEST");
}Example 3
| Project: boot-stateless-auth-master File: StatelessAuthentication.java View source code |
@Bean
public InitializingBean insertDefaultUsers() {
return new InitializingBean() {
@Autowired
private UserRepository userRepository;
@Override
public void afterPropertiesSet() {
addUser("admin", "admin");
addUser("user", "user");
}
private void addUser(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(new BCryptPasswordEncoder().encode(password));
user.grantRole(username.equals("admin") ? UserRole.ADMIN : UserRole.USER);
userRepository.save(user);
}
};
}Example 4
| Project: cambodia-master File: TestBusiFeeService.java View source code |
@Autowired
@Before
public void setUp() throws Exception {
Map extraContext = new HashMap();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
servletContext = new MockServletContext();
extraContext.put(HTTP_REQUEST, request);
extraContext.put(HTTP_RESPONSE, response);
extraContext.put(SERVLET_CONTEXT, servletContext);
actionContext = new ActionContext(extraContext);
ServletActionContext.setContext(actionContext);
}Example 5
| Project: cas-master File: OidcConfiguration.java View source code |
@Autowired
@RefreshScope
@Bean
public CasWebflowEventResolver oidcAuthenticationContextWebflowEventResolver(@Qualifier("defaultAuthenticationSystemSupport") final AuthenticationSystemSupport authenticationSystemSupport) {
final CasWebflowEventResolver r = new OidcAuthenticationContextWebflowEventEventResolver(authenticationSystemSupport, centralAuthenticationService, servicesManager, ticketRegistrySupport, warnCookieGenerator, authenticationRequestServiceSelectionStrategies, multifactorAuthenticationProviderSelector);
this.initialAuthenticationAttemptWebflowEventResolver.addDelegate(r);
return r;
}Example 6
| Project: jeffaschenk-commons-master File: SystemEnvironment.java View source code |
public synchronized void setSystemEnvironmentProperties(Properties systemEnvironmentProperties) {
if (this.systemEnvironmentProperties != null) {
log.info("System Environment Properties Bean has been Autowired, refreshing Properties.");
} else {
log.info("System Environment Properties Bean setting Initial Properties.");
}
// *****************************************
// Establish Delegate ClassLoader
systemEnvironmentClassLoader = ClassLoader.getSystemClassLoader();
// *****************************************
// Perform the Set.
this.systemEnvironmentProperties = systemEnvironmentProperties;
}Example 7
| Project: spring-hadoop-master File: DatasetTemplatePartitioningParquetTests.java View source code |
@Autowired
public void setDatasetOperations(DatasetOperations datasetOperations) {
PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().year("birthDate").month("birthDate").build();
((DatasetTemplate) datasetOperations).setDatasetDefinitions(Arrays.asList(new DatasetDefinition[] { new DatasetDefinition(SimplePojo.class, "parquet", partitionStrategy) }));
this.datasetOperations = datasetOperations;
}Example 8
| Project: test4j-master File: SpringBeanInjectorByAutowired.java View source code |
/**
* {@inheritDoc}<br>
* <br>
* æ ¹æ?®@SpringBeanByType注入spring bean<br>
*/
@Override
public void injectBy(Test4JBeanFactory beanFactory, Object testedObject) {
Class testedClazz = testedObject.getClass();
Set<Field> fields = getFieldsAnnotatedWith(testedClazz, Autowired.class);
for (Field field : fields) {
try {
Object bean = getSpringBeanByType(beanFactory, field.getType());
FieldHelper.setFieldValue(testedObject, field, bean);
} catch (Throwable e) {
String error = String.format("inject @SpringBeanByType field[%s] in class[%s] error.", field.getName(), testedClazz.getName());
throw new Test4JException(error, e);
}
}
}Example 9
| Project: devicehive-java-server-master File: RdbmsPersistenceConfig.java View source code |
@Bean
@Autowired
@DependsOn(value = { "simpleApplicationContextHolder" })
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factoryBean.setValidationMode(ValidationMode.CALLBACK);
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan("com.devicehive.model");
final Properties props = new Properties();
props.putAll(this.properties.getHibernateProperties(this.dataSource));
factoryBean.setJpaProperties(props);
return factoryBean;
}Example 10
| Project: DSpace-master File: RDFConverterImpl.java View source code |
@Autowired(required = true)
public void setPlugins(List<ConverterPlugin> plugins) {
this.plugins = plugins;
if (log.isDebugEnabled()) {
StringBuilder pluginNames = new StringBuilder();
for (ConverterPlugin plugin : plugins) {
if (pluginNames.length() > 0) {
pluginNames.append(", ");
}
pluginNames.append(plugin.getClass().getCanonicalName());
}
log.debug("Loaded the following plugins: " + pluginNames.toString());
}
}Example 11
| Project: edison-microservice-master File: InMemoryFeatureStateRepositoryConfiguration.java View source code |
private StateRepository createInMemoryStateRepository() {
return new StateRepository() {
Logger LOG = getLogger(TogglzConfiguration.class);
private Map<String, FeatureState> featureStore = new ConcurrentHashMap<>();
@Autowired
UserProvider userProvider;
@Override
public FeatureState getFeatureState(final Feature feature) {
if (featureStore.containsKey(feature.name())) {
return featureStore.get(feature.name());
}
return new FeatureState(feature, false);
}
@Override
public void setFeatureState(final FeatureState featureState) {
featureStore.put(featureState.getFeature().name(), featureState);
LOG.info((!StringUtils.isEmpty(userProvider.getCurrentUser().getName()) ? "User '" + userProvider.getCurrentUser().getName() + "'" : "Unknown user") + (featureState.isEnabled() ? " enabled " : " disabled ") + "feature " + featureState.getFeature().name());
}
};
}Example 12
| Project: iupload-master File: AppConfiguration.java View source code |
@Bean
@Autowired
public UserPermissionProvider permissionProvider(FileSystemProxy fileSystemProxy) throws IOException {
if ("true".equalsIgnoreCase(useDefaultPermissionProvider)) {
return new DefaultUserPermissionProvider();
} else {
final UserPermissionConfigLoader loader;
loader = new FileSystemUserPermissionConfigLoader(fileSystemProxy);
return new FileBasedUserPermissionProvider(loader);
}
}Example 13
| Project: Java-Examples-master File: SpringHazelcastApplication.java View source code |
@Bean
@Autowired
public HazelcastInstance getHazelcastInstance(MapStore<String, User> userMapStore) {
final Config config = new Config();
final NetworkConfig networkConfig = new NetworkConfig();
networkConfig.setPort(5701);
networkConfig.setPortAutoIncrement(true);
config.setNetworkConfig(networkConfig);
final JoinConfig joinConfig = new JoinConfig();
networkConfig.setJoin(joinConfig);
final MulticastConfig multicastConfig = new MulticastConfig();
multicastConfig.setEnabled(false);
joinConfig.setMulticastConfig(multicastConfig);
final TcpIpConfig tcpIpConfig = new TcpIpConfig();
tcpIpConfig.setEnabled(false);
joinConfig.setTcpIpConfig(tcpIpConfig);
final AwsConfig awsConfig = new AwsConfig();
awsConfig.setEnabled(false);
joinConfig.setAwsConfig(awsConfig);
final SSLConfig sslConfig = new SSLConfig();
sslConfig.setEnabled(false);
networkConfig.setSSLConfig(sslConfig);
final MapConfig mapConfig = new MapConfig();
mapConfig.setName("userMap");
final MapStoreConfig mapStoreConfig = new MapStoreConfig();
mapStoreConfig.setEnabled(true);
mapStoreConfig.setWriteDelaySeconds(60);
mapStoreConfig.setInitialLoadMode(MapStoreConfig.InitialLoadMode.LAZY);
mapStoreConfig.setImplementation(userMapStore);
mapConfig.setMapStoreConfig(mapStoreConfig);
config.addMapConfig(mapConfig);
return Hazelcast.newHazelcastInstance(config);
}Example 14
| Project: owsi-core-parent-master File: TestTransactionSynchronization.java View source code |
@Autowired
private void setTransactionTemplate(PlatformTransactionManager transactionManager) {
DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED);
writeTransactionAttribute.setReadOnly(false);
writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute);
DefaultTransactionAttribute writeRequiresNewTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRES_NEW);
writeRequiresNewTransactionAttribute.setReadOnly(false);
writeRequiresNewTransactionTemplate = new TransactionTemplate(transactionManager, writeRequiresNewTransactionAttribute);
DefaultTransactionAttribute readOnlyTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED);
readOnlyTransactionAttribute.setReadOnly(true);
readOnlyTransactionTemplate = new TransactionTemplate(transactionManager, readOnlyTransactionAttribute);
}Example 15
| Project: smock-master File: SecuredEndpointTest.java View source code |
@Autowired
public void setApplicationContext(ApplicationContext context) {
Wss4jSecurityInterceptor securityInterceptor = new Wss4jSecurityInterceptor();
securityInterceptor.setSecurementActions("UsernameToken Timestamp");
securityInterceptor.setSecurementUsername("Bert");
securityInterceptor.setSecurementPassword("Ernie");
this.interceptors = new ClientInterceptor[] { securityInterceptor };
wsMockClient = createClient(context, interceptors);
}Example 16
| Project: spring-boot-master File: MockitoAopProxyTargetInterceptor.java View source code |
@Autowired
public static void applyTo(Object source) {
Assert.state(AopUtils.isAopProxy(source), "Source must be an AOP proxy");
try {
Advised advised = (Advised) source;
for (Advisor advisor : advised.getAdvisors()) {
if (advisor instanceof MockitoAopProxyTargetInterceptor) {
return;
}
}
Object target = AopTestUtils.getUltimateTargetObject(source);
Advice advice = new MockitoAopProxyTargetInterceptor(source, target);
advised.addAdvice(0, advice);
} catch (Exception ex) {
throw new IllegalStateException("Unable to apply Mockito AOP support", ex);
}
}Example 17
| Project: spring-framework-issues-master File: DelegatingWebMvcConfigurationWithOtherAutowiredDependenciesTests.java View source code |
@Bean
TestWebMvcConfigurer testWebMvcConfigurerWithContentNegotiationManager() {
return new TestWebMvcConfigurer() {
@Autowired
ApplicationContext context;
@Autowired
@Lazy
private ContentNegotiationManager contentNegotiationManager;
@Autowired
@Lazy
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
@Autowired
@Lazy
private HandlerExceptionResolver handlerExceptionResolver;
@Autowired(required = false)
private List<HttpMessageConverter<?>> httpMessageConverters;
private final HandlerMethodArgumentResolver testWebArgumentResolver = new ServletWebArgumentResolverAdapter(new TestWebArgumentResolver());
/**
* Using @Lazy initialization in the autowired dependencies above, this test
* looks to make sure all of the following methods get called.
*/
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
interceptorRegistry.addInterceptor(new TestHandlerInterceptor());
super.addInterceptors(interceptorRegistry);
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
list.add(this.testWebArgumentResolver);
super.addArgumentResolvers(list);
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
contentNegotiationConfigurer.defaultContentType(MediaType.APPLICATION_JSON);
super.configureContentNegotiation(contentNegotiationConfigurer);
}
@PostConstruct
public void testPostConstruct() {
org.springframework.util.Assert.notNull(this.context, "context may not be null");
org.springframework.util.Assert.notNull(this.contentNegotiationManager, "contentNegotiationManager may not be null");
org.springframework.util.Assert.notNull(this.requestMappingHandlerAdapter, "requestMappingHandlerAdapter may not be null");
org.springframework.util.Assert.notNull(this.handlerExceptionResolver, "handlerExceptionResolver may not be null");
if (this.httpMessageConverters == null) {
//For Non-Spring Boot Applications
this.httpMessageConverters = this.requestMappingHandlerAdapter.getMessageConverters();
}
org.springframework.util.Assert.notNull(httpMessageConverters, "httpMessageConverters may not be null");
//Add test returnValueHandler
final TestHandlerMethodReturnValueHandler testHandlerMethodReturnValueHandler = new TestHandlerMethodReturnValueHandler(httpMessageConverters, contentNegotiationManager);
final List<HandlerMethodReturnValueHandler> handlers = new ArrayList<HandlerMethodReturnValueHandler>(this.requestMappingHandlerAdapter.getReturnValueHandlers());
handlers.add(0, testHandlerMethodReturnValueHandler);
this.requestMappingHandlerAdapter.setReturnValueHandlers(handlers);
//Add test handlerExceptionResolver
ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver = new ExceptionHandlerExceptionResolver();
exceptionHandlerExceptionResolver.setApplicationContext(this.context);
exceptionHandlerExceptionResolver.setContentNegotiationManager(this.contentNegotiationManager);
exceptionHandlerExceptionResolver.setCustomReturnValueHandlers(new ArrayList<HandlerMethodReturnValueHandler>() {
{
add(testHandlerMethodReturnValueHandler);
}
});
exceptionHandlerExceptionResolver.setMessageConverters(httpMessageConverters);
exceptionHandlerExceptionResolver.setCustomArgumentResolvers(new ArrayList<HandlerMethodArgumentResolver>() {
{
add(testWebArgumentResolver);
}
});
exceptionHandlerExceptionResolver.afterPropertiesSet();
HandlerExceptionResolverComposite handlerExceptionResolverComposite = (HandlerExceptionResolverComposite) this.handlerExceptionResolver;
final List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<HandlerExceptionResolver>(handlerExceptionResolverComposite.getExceptionResolvers());
exceptionResolvers.add(0, exceptionHandlerExceptionResolver);
handlerExceptionResolverComposite.setExceptionResolvers(exceptionResolvers);
}
};
}Example 18
| Project: wampspring-demos-master File: WebSecurityConfig.java View source code |
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new AuthenticationProvider() {
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
return new UsernamePasswordAuthenticationToken(token.getName(), token.getCredentials(), SECURE_ADMIN_PASSWORD.equals(token.getCredentials()) ? AuthorityUtils.createAuthorityList("ADMIN") : null);
}
});
}Example 19
| Project: com.idega.block.process-master File: CaseManagersProvider.java View source code |
@Autowired(required = false)
public void setCaseManagers(List<CasesRetrievalManager> caseManagers) {
for (CasesRetrievalManager caseManager : caseManagers) {
String beanIdentifier = caseManager.getBeanIdentifier();
if (beanIdentifier == null)
Logger.getLogger(getClass().getName()).log(Level.WARNING, "No bean identifier provided for case handler. Skipping. Class name: " + caseManager.getClass().getName());
else
getCaseHandlersTypesBeanIdentifiers().put(caseManager.getType(), beanIdentifier);
}
}Example 20
| Project: coprhd-controller-master File: DefaultExecutionServiceFactory.java View source code |
@Autowired
public void setServices(List<ExecutionService> values) {
LOG.info("Loading Services");
for (ExecutionService service : values) {
Class<? extends ExecutionService> serviceClass = service.getClass();
Service serviceDef = serviceClass.getAnnotation(Service.class);
if (serviceDef != null) {
String serviceName = serviceDef.value();
services.put(serviceName, serviceClass);
LOG.debug(String.format("Added Service '%s' => %s", serviceName, serviceClass.getName()));
} else {
LOG.warn(String.format("Service '%s' is missing a %s annotation", serviceClass.getName(), Service.class.getSimpleName()));
}
}
}Example 21
| Project: elmis-master File: MySwaggerConfig.java View source code |
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
// this avoids the duplicate api endpoints on the swagger ui.
do {
this.springSwaggerConfig.swaggerRequestMappingHandlerMappings().remove(1);
} while (this.springSwaggerConfig.swaggerRequestMappingHandlerMappings().size() > 1);
}Example 22
| Project: etm-core-master File: BorderPage.java View source code |
@Autowired
public void setControllerMonitor(ControllerMonitor controllerMonitor) {
ControllerInstance controller = controllerMonitor.getLocalController();
addControl(new ControllerInfoPanel("controllerInfoPanel", controller));
FailoverState failoverState = controller != null ? controller.getFailoverState() : null;
addControl(new FailoverWarningPanel("failoverWarningPanel", failoverState));
}Example 23
| Project: iMatrix6.0.0Dev-master File: FunctionManager.java View source code |
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
functionDao = new SimpleHibernateTemplate<Function, Long>(sessionFactory, Function.class);
roleDao = new SimpleHibernateTemplate<Role, Long>(sessionFactory, Role.class);
role_fDao = new SimpleHibernateTemplate<RoleFunction, Long>(sessionFactory, RoleFunction.class);
roleDao = new SimpleHibernateTemplate<Role, Long>(sessionFactory, Role.class);
}Example 24
| Project: modeshape-examples-master File: SecurityConfig.java View source code |
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
UserDetails admin = new User("admin", "123", Arrays.asList(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("readonly"), new SimpleGrantedAuthority("readwrite")));
UserDetails user1 = new User("user1", "123", Arrays.asList(new SimpleGrantedAuthority("readonly"), new SimpleGrantedAuthority("readwrite")));
UserDetails user2 = new User("user2", "123", Arrays.asList(new SimpleGrantedAuthority("readonly")));
UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(Arrays.asList(admin, user1, user2));
auth.userDetailsService(userDetailsManager);
}Example 25
| Project: proctor-pipet-master File: AppConfig.java View source code |
@Bean
@Autowired
public VariableConfiguration variableConfiguration(final JsonPipetConfig jsonPipetConfig) {
return VariableConfigurationJsonParser.newParser().registerStandardConverters().registerValueConverterByCanonicalName(// Custom types for UserAgent
UserAgentValueConverter.userAgentValueConverter()).registerValueConverterBySimpleName(UserAgentValueConverter.userAgentValueConverter()).buildFrom(jsonPipetConfig);
}Example 26
| Project: saos-master File: CcjImportJobConfiguration.java View source code |
@Bean
@Autowired
protected Step ccJudgmentImportProcessStep() {
TaskletStep step = steps.get("ccJudgmentImportProcessStep").<RawSourceCcJudgment, JudgmentWithCorrectionList<CommonCourtJudgment>>chunk(20).faultTolerant().skipPolicy(ccjImportProcessSkipPolicy).listener(ccjImportProcessSkipListener).reader(ccjImportProcessReader).processor(ccjImportProcessProcessor).writer(ccjImportProcessWriter()).transactionAttribute(new DefaultTransactionAttribute()).build();
step.setTransactionAttribute(new DefaultTransactionAttribute());
return step;
}Example 27
| Project: spring-batch-master File: SpringAutowiredAnnotationBeanPostProcessor.java View source code |
@Override
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
synchronized (this.candidateConstructorsCache) {
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors();
List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length);
Constructor<?> requiredConstructor = null;
Constructor<?> defaultConstructor = null;
for (Constructor<?> candidate : rawCandidates) {
Annotation annotation = findAutowiredAnnotation(candidate);
if (annotation != null) {
if (requiredConstructor != null) {
throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
}
if (candidate.getParameterTypes().length == 0) {
throw new IllegalStateException("Autowired annotation requires at least one argument: " + candidate);
}
boolean required = determineRequiredStatus(annotation);
if (required) {
if (!candidates.isEmpty()) {
throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
}
requiredConstructor = candidate;
}
candidates.add(candidate);
} else if (candidate.getParameterTypes().length == 0) {
defaultConstructor = candidate;
}
}
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
if (requiredConstructor == null && defaultConstructor != null) {
candidates.add(defaultConstructor);
}
candidateConstructors = candidates.toArray(new Constructor[candidates.size()]);
} else {
candidateConstructors = new Constructor[0];
}
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}Example 28
| Project: spring-framework-master File: SpringJUnit4ClassRunnerAppCtxTests.java View source code |
@Test
public final void verifyAnnotationAutowiredAndInjectedFields() {
assertNull("The nonrequiredLong field should NOT have been autowired.", this.nonrequiredLong);
assertEquals("The quux field should have been autowired via @Autowired and @Qualifier.", "Quux", this.quux);
assertEquals("The namedFoo field should have been injected via @Inject and @Named.", "Quux", this.namedQuux);
assertSame("@Autowired/@Qualifier and @Inject/@Named quux should be the same object.", this.quux, this.namedQuux);
assertNotNull("The pet field should have been autowired.", this.autowiredPet);
assertNotNull("The pet field should have been injected.", this.injectedPet);
assertEquals("Fido", this.autowiredPet.getName());
assertEquals("Fido", this.injectedPet.getName());
assertSame("@Autowired and @Inject pet should be the same object.", this.autowiredPet, this.injectedPet);
}Example 29
| Project: spring4-1-showcase-master File: YamlTest.java View source code |
@Test
public void testYmlMap() {
//Map£¨²»ÄÜÖ±½Ó×¢Èë@Autowired Map£©
//Çë²Î¿¼ MapÒÀÀµ×¢È루http://jinnianshilongnian.iteye.com/blog/1989379£©
System.out.println(this.yamlMap);
Map<String, Object> yamlMap = ctx.getBean("yamlMap", Map.class);
//ÐèÒªsnakeyaml ¸Ã¹¦ÄÜÊÇ´Óspring-bootÒýÈëµÄ
Map<String, Object> env = (Map<String, Object>) yamlMap.get("env");
Map<String, Object> one = (Map<String, Object>) env.get("one");
Assert.assertEquals("zhangsan", one.get("name"));
List<Map<String, Object>> two = (List) env.get("two");
Assert.assertEquals(1, two.get(0).get("a"));
Assert.assertEquals("3", two.get(1).get("c"));
Assert.assertEquals(null, env.get("three"));
//Properties
Assert.assertEquals("zhangsan", yamlProperties.getProperty("env.one.name"));
//getPropertyÈç¹û·µ»ØµÄÊý¾Ýʱ·ÇStringµÄÔò·µ»Ønull
Assert.assertEquals(1, yamlProperties.get("env.two[0].a"));
Assert.assertEquals("3", yamlProperties.getProperty("env.two[1].c"));
Assert.assertEquals("", yamlProperties.getProperty("env.three"));
//spring.profiles
//http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-yaml
}Example 30
| Project: Trainings-master File: SecurityConfig.java View source code |
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder()).usersByUsernameQuery("select login, password, 'true' as enabled from authentification where login = ?").authoritiesByUsernameQuery("select an.login, us.role from users us join authentification an on us.id = an.user_id where an.login = ?");
}Example 31
| Project: assertj-db-master File: AbstractH2Test.java View source code |
@Autowired(required = true)
protected void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.dataSourceDDD = new DataSourceWithLetterCase(dataSource, LetterCase.TABLE_DEFAULT, LetterCase.COLUMN_DEFAULT, LetterCase.PRIMARY_KEY_DEFAULT);
this.dataSourceUIUIUI = new DataSourceWithLetterCase(dataSource, letterCaseUI, letterCaseUI, letterCaseUI);
this.dataSourceNSNSNS = new DataSourceWithLetterCase(dataSource, letterCaseNS, letterCaseNS, letterCaseNS);
}Example 32
| Project: constretto-core-master File: AssemblyWithConcreteClassesTest.java View source code |
@Test
public void injectionUsingConstrettoWithEnvironmentSetAndUsinginterface() {
class MyConsumer {
@Autowired
CommonInterface commonInterface;
}
setProperty(ASSEMBLY_KEY, "stub");
ApplicationContext ctx = loadContextAndInjectWithConstretto();
MyConsumer consumer = new MyConsumer();
ctx.getAutowireCapableBeanFactory().autowireBean(consumer);
Assert.assertEquals(consumer.commonInterface.getClass(), CommonInterfaceStub.class);
}Example 33
| Project: genie-master File: SecurityConfig.java View source code |
/**
* Configure the global authentication manager.
*
* @param auth The builder to configure
* @throws Exception on error
*/
@Autowired
protected void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
if (this.providers != null) {
for (final AuthenticationProvider provider : this.providers) {
log.debug("Adding authentication provider {} to authentication provider.", provider.toString());
auth.authenticationProvider(provider);
}
} else {
// in the case nothing was configured
log.debug("No providers were found. Configuring in memory authentication to avoid NPE.");
auth.inMemoryAuthentication();
}
}Example 34
| Project: geo-platform-master File: GPSpringVelocityEngineConfig.java View source code |
@Bean(name = "gpSpringVelocityEngine")
@Scope(value = "prototype")
@Autowired
public VelocityEngine gpVelocityEngine(@Qualifier(value = "gpVelocityParserPollSize") GPVelocityParserPollSize gpVelocityParserPollSize) throws VelocityException, IOException {
logger.debug("\n\n@@@@@@@@@@@@@@@@@@@CONFIGURING VELOCITY POOL PARSER " + "with : {}\n\n", gpVelocityParserPollSize);
VelocityEngineFactory factory = new VelocityEngineFactory();
Properties props = new Properties();
props.put("resource.loader", "class");
props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader." + "ClasspathResourceLoader");
props.put("parser.pool.class", "org.apache.velocity.runtime.ParserPoolImpl");
props.put("parser.pool.size", gpVelocityParserPollSize.getPoolSize());
factory.setVelocityProperties(props);
return factory.createVelocityEngine();
}Example 35
| Project: Glue-master File: GlueFactory.java View source code |
/**
* inject action of spring
* @param instance
*/
private void injectService(Object instance) {
if (instance == null) {
return;
}
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
Object fieldBean = null;
// with bean-id, bean could be found by both @Resource and @Autowired, or bean could only be found by @Autowired
if (AnnotationUtils.getAnnotation(field, Resource.class) != null) {
try {
Resource resource = AnnotationUtils.getAnnotation(field, Resource.class);
if (resource.name() != null && resource.name().length() > 0) {
fieldBean = XxlJobExecutor.applicationContext.getBean(resource.name());
} else {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getName());
}
} catch (Exception e) {
}
if (fieldBean == null) {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getType());
}
} else if (AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
Qualifier qualifier = AnnotationUtils.getAnnotation(field, Qualifier.class);
if (qualifier != null && qualifier.value() != null && qualifier.value().length() > 0) {
fieldBean = XxlJobExecutor.applicationContext.getBean(qualifier.value());
} else {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getType());
}
}
if (fieldBean != null) {
field.setAccessible(true);
try {
field.set(instance, fieldBean);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}Example 36
| Project: inspectIT-master File: SpringConfiguration.java View source code |
/**
* @param threadTransformHelper
* {@link IThreadTransformHelper}
* @return Returns socketReadExecutorService
*/
@Bean(name = "socketReadExecutorService")
@Scope(BeanDefinition.SCOPE_SINGLETON)
@Autowired
public ExecutorService getSocketReadExecutorService(final IThreadTransformHelper threadTransformHelper) {
ThreadFactory inspectitThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new AgentAwareThread(r, threadTransformHelper);
}
};
ThreadFactory threadFactory = new ThreadFactoryBuilder().setThreadFactory(inspectitThreadFactory).setNameFormat("inspectit-socket-read-executor-service-thread-%d").setDaemon(true).build();
return Executors.newFixedThreadPool(1, threadFactory);
}Example 37
| Project: jena-sparql-api-master File: ConfigSparqlExportJob.java View source code |
@Bean
@StepScope
@Autowired
public ItemReaderSparqlPaging<Binding> reader(Query query, QueryExecutionFactory qef, // @Value("#{jobParameters[defaultGraphUris]}") String defaultGraphUris,
@Value("#{jobParameters[queryString]}") String queryString) {
ItemReaderSparqlPaging<Binding> itemReader = new ItemReaderSparqlPaging<Binding>();
itemReader.setSparqlService(qef);
itemReader.setBindingMapper(new BindingMapperPassThrough());
itemReader.setQuery(query);
itemReader.setPageSize(chunkSize);
itemReader.setSaveState(true);
return itemReader;
}Example 38
| Project: LinkedGeoData-master File: AppConfig.java View source code |
@Bean
@Autowired
public SparqlServiceFactory sparqlServiceFactory(DataSource dataSource) {
CacheBackendDao dao = new CacheBackendDaoPostgres();
CacheBackend cacheBackend = new CacheBackendDataSource(dataSource, dao);
CacheFrontend cacheFrontend = new CacheFrontendImpl(cacheBackend);
SparqlServiceFactory result = new SparqlServiceFactoryImpl(cacheFrontend);
return result;
}Example 39
| Project: speedment-master File: GeneratedConfigurationTranslator.java View source code |
@Override
protected Class makeCodeGenModel(File file) {
return newBuilder(file, getClassOrInterfaceName()).forEveryProject(( clazz, project) -> {
clazz.public_();
// Add constants
clazz.add(Field.of("URL_PROPERTY", String.class).protected_().final_().static_().set(Value.ofText("jdbc.url")));
clazz.add(Field.of("USERNAME_PROPERTY", String.class).protected_().final_().static_().set(Value.ofText("jdbc.username")));
clazz.add(Field.of("PASSWORD_PROPERTY", String.class).protected_().final_().static_().set(Value.ofText("jdbc.password")));
// Add environment variable
clazz.add(Field.of("env", Environment.class).protected_().add(AnnotationUsage.of(Autowired.class)));
// Add application bean
final Type appType = SimpleType.create(getSupport().basePackageName() + "." + getSupport().typeName() + "Application");
final String appBuilder = getSupport().typeName() + "ApplicationBuilder";
final Type appBuilderType = SimpleType.create(getSupport().basePackageName() + "." + appBuilder);
file.add(Import.of(appBuilderType));
clazz.add(Method.of("application", appType).public_().add(AnnotationUsage.of(Bean.class)).add("final " + appBuilder + " builder =", " new " + appBuilder + "();", "", "if (env.containsProperty(URL_PROPERTY)) {", " builder.withConnectionUrl(env.getProperty(URL_PROPERTY));", "}", "", "if (env.containsProperty(USERNAME_PROPERTY)) {", " builder.withUsername(env.getProperty(USERNAME_PROPERTY));", "}", "", "if (env.containsProperty(PASSWORD_PROPERTY)) {", " builder.withPassword(env.getProperty(PASSWORD_PROPERTY));", "}", "", "return builder.build();"));
// Add manager beans
traverseOver(project, Table.class).filter(HasEnabled::isEnabled).forEachOrdered( table -> {
final TranslatorSupport<Table> support = new TranslatorSupport<>(injector, table);
file.add(Import.of(support.entityType()));
clazz.add(Method.of(support.variableName(), support.managerType()).public_().add(Field.of("app", appType)).add(AnnotationUsage.of(Bean.class)).add("return app.getOrThrow(" + support.managerTypeName() + ".class);"));
});
}).build();
}Example 40
| Project: spock-master File: SpringExtension.java View source code |
private void checkNoSharedFieldsInjected(SpecInfo spec) {
for (FieldInfo field : spec.getAllFields()) {
if (field.getReflection().isAnnotationPresent(Shared.class) && (field.getReflection().isAnnotationPresent(Autowired.class) || // avoid compile-time dependency on optional classes
ReflectionUtil.isAnnotationPresent(field.getReflection(), "javax.annotation.Resource") || ReflectionUtil.isAnnotationPresent(field.getReflection(), "javax.inject.Inject")))
throw new SpringExtensionException("@Shared field '%s' cannot be injected; use an instance field instead").withArgs(field.getName());
}
}Example 41
| Project: spring-security-oauth-master File: Application.java View source code |
@Bean
protected ResourceServerConfiguration adminResources() {
ResourceServerConfiguration resource = new ResourceServerConfiguration() {
// Switch off the Spring Boot @Autowired configurers
public void setConfigurers(List<ResourceServerConfigurer> configurers) {
super.setConfigurers(configurers);
}
};
resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("oauth2/admin");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/admin/**").authorizeRequests().anyRequest().access("#oauth2.hasScope('read')");
}
}));
resource.setOrder(3);
return resource;
}Example 42
| Project: spring-security-scribe-master File: SecurityConfig.java View source code |
@Bean
@Autowired
public ScribeAuthenticationFilter authFilterBean(AuthenticationManager authManager) {
ScribeAuthenticationFilter filter = new ScribeAuthenticationFilter("/oauth-login");
//filter.setConfigMatchParameter("atype");
filter.setAuthenticationManager(authManager);
filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login-error"));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/login-success"));
FacebookProviderConfiguration facebookProvider = new FacebookProviderConfiguration();
facebookProvider.setApiKey("12345678");
facebookProvider.setApiSecret("xxxxxxxxxxxxxxxxxxxxxxxx");
List<ProviderConfiguration> config = new ArrayList<>(1);
config.add(facebookProvider);
filter.setProviderConfigurations(config);
return filter;
}Example 43
| Project: spring-social-master File: SocialConfiguration.java View source code |
@Autowired
public void setSocialConfigurers(List<SocialConfigurer> socialConfigurers) {
Assert.notNull(socialConfigurers, "At least one configuration class must implement SocialConfigurer (or subclass SocialConfigurerAdapter)");
Assert.notEmpty(socialConfigurers, "At least one configuration class must implement SocialConfigurer (or subclass SocialConfigurerAdapter)");
this.socialConfigurers = socialConfigurers;
}Example 44
| Project: uPortal-master File: VersionedDataUpdaterImpl.java View source code |
@Autowired
public void setVersionedDatabaseUpdateHelpers(Collection<IVersionedDatabaseUpdateHelper> helpers) {
this.databaseUpdateHelpers = new HashMap<String, SortedSet<IVersionedDatabaseUpdateHelper>>();
for (final IVersionedDatabaseUpdateHelper helper : helpers) {
final String databaseName = helper.getDatabaseName();
SortedSet<IVersionedDatabaseUpdateHelper> updaters = this.databaseUpdateHelpers.get(databaseName);
if (updaters == null) {
updaters = new TreeSet<IVersionedDatabaseUpdateHelper>(VersionedDatabaseUpdateHelperComparator.INSTANCE);
this.databaseUpdateHelpers.put(databaseName, updaters);
}
updaters.add(helper);
}
}Example 45
| Project: vertx-examples-master File: ExampleSpringConfiguration.java View source code |
@Bean
@Autowired
public DataSource dataSource(DatabasePopulator populator) {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
DatabasePopulatorUtils.execute(populator, dataSource);
return dataSource;
}Example 46
| Project: xxl-job-master File: GlueFactory.java View source code |
/**
* inject action of spring
* @param instance
*/
private void injectService(Object instance) {
if (instance == null) {
return;
}
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
Object fieldBean = null;
// with bean-id, bean could be found by both @Resource and @Autowired, or bean could only be found by @Autowired
if (AnnotationUtils.getAnnotation(field, Resource.class) != null) {
try {
Resource resource = AnnotationUtils.getAnnotation(field, Resource.class);
if (resource.name() != null && resource.name().length() > 0) {
fieldBean = XxlJobExecutor.applicationContext.getBean(resource.name());
} else {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getName());
}
} catch (Exception e) {
}
if (fieldBean == null) {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getType());
}
} else if (AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
Qualifier qualifier = AnnotationUtils.getAnnotation(field, Qualifier.class);
if (qualifier != null && qualifier.value() != null && qualifier.value().length() > 0) {
fieldBean = XxlJobExecutor.applicationContext.getBean(qualifier.value());
} else {
fieldBean = XxlJobExecutor.applicationContext.getBean(field.getType());
}
}
if (fieldBean != null) {
field.setAccessible(true);
try {
field.set(instance, fieldBean);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}Example 47
| Project: 5.2.0.RC-master File: LogManager.java View source code |
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
logDao = new SimpleHibernateTemplate<Log, Long>(sessionFactory, Log.class);
loginUserLogDao = new SimpleHibernateTemplate<LoginLog, Long>(sessionFactory, LoginLog.class);
securitySetDao = new SimpleHibernateTemplate<SecuritySetting, Long>(sessionFactory, SecuritySetting.class);
logUtilDao = new LogUtilDao(sessionFactory);
}Example 48
| Project: artifact-listener-master File: MavenArtifactNotifierWebappSecurityConfig.java View source code |
@Autowired
@Bean
public ClientAuthenticationFilter clientAuthenticationFilter(AuthenticationManager authenticationManager, Clients clients) {
ClientAuthenticationFilter filter = new ClientAuthenticationFilter("/" + Pac4jAuthenticationUtils.CALLBACK_URI);
filter.setClients(clients);
filter.setAuthenticationManager(authenticationManager);
filter.setAuthenticationFailureHandler(pac4jAuthenticationFailureHandler());
filter.setAuthenticationSuccessHandler(pac4jAuthenticationSuccessHandler());
return filter;
}Example 49
| Project: AxonFramework-master File: AxonAutoConfiguration.java View source code |
@Autowired
public void configureEventHandling(EventHandlingConfiguration eventHandlingConfiguration, ApplicationContext applicationContext) {
eventProcessorProperties.getProcessors().forEach(( k, v) -> {
if (v.getMode() == EventProcessorProperties.Mode.TRACKING) {
if (v.getSource() == null) {
eventHandlingConfiguration.registerTrackingProcessor(k);
} else {
eventHandlingConfiguration.registerTrackingProcessor(k, c -> applicationContext.getBean(v.getSource(), StreamableMessageSource.class));
}
} else {
if (v.getSource() == null) {
eventHandlingConfiguration.registerSubscribingEventProcessor(k);
} else {
eventHandlingConfiguration.registerSubscribingEventProcessor(k, c -> applicationContext.getBean(v.getSource(), SubscribableMessageSource.class));
}
}
});
}Example 50
| Project: BlackboardVCPortlet-master File: DelegatingPermissionEvaluator.java View source code |
@Autowired
public void setPermissionTesters(Set<PermissionTester<Object>> permissionTesters) {
final Builder<Class<Object>, PermissionTester<Object>> testersBuilder = ImmutableMap.builder();
for (final PermissionTester<Object> permissionTester : permissionTesters) {
testersBuilder.put(permissionTester.getDomainObjectType(), permissionTester);
}
this.permissionTesterResolutionCache = new ConcurrentHashMap<Class<? extends Object>, PermissionTester<Object>>();
this.permissionTesters = testersBuilder.build();
}Example 51
| Project: cas-client-autoconfig-support-master File: CasClientConfiguration.java View source code |
@Autowired(required = false)
void setConfigurers(Collection<CasClientConfigurer> configurers) {
if (CollectionUtils.isEmpty(configurers)) {
return;
}
if (configurers.size() > 1) {
throw new IllegalStateException(configurers.size() + " implementations of " + "CasClientConfigurer were found when only 1 was expected. " + "Refactor the configuration such that CasClientConfigurer is " + "implemented only once or not at all.");
}
this.casClientConfigurer = configurers.iterator().next();
}Example 52
| Project: cevent-app-master File: SpringReloader.java View source code |
public void reloadEvent(String typename, Class<?> clazz) {
log.trace("Hot reloading - checking if this is a Spring bean: " + typename);
Annotation annotation = AnnotationUtils.findAnnotation(clazz, Component.class);
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(clazz, RestController.class);
}
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(clazz, Controller.class);
}
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(clazz, Service.class);
}
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(clazz, Repository.class);
}
if (annotation != null) {
log.debug("This is a Spring Bean, annotation=" + annotation.annotationType());
try {
Object beanInstance = applicationContext.getBean(clazz);
// We only support autowiring on fields
log.debug("Existing bean, autowiring fields");
if (AopUtils.isCglibProxy(beanInstance)) {
log.trace("This is a CGLIB proxy, getting the real object");
beanInstance = ((Advised) beanInstance).getTargetSource().getTarget();
} else if (AopUtils.isJdkDynamicProxy(beanInstance)) {
log.trace("This is a JDK proxy, getting the real object");
beanInstance = ((Advised) beanInstance).getTargetSource().getTarget();
}
Field[] fields = beanInstance.getClass().getDeclaredFields();
for (Field field : fields) {
Annotation[] annotations = field.getDeclaredAnnotations();
if (AnnotationUtils.getAnnotation(field, Inject.class) != null || AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
log.debug("@Inject annotation found on field {}", field.getName());
Object beanToInject = applicationContext.getBean(field.getType());
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, beanInstance, beanToInject);
}
}
// TODO check aspects, at least @Transactional and @RolesAllowed
// aspects already work at the class level, ie @Transactional at the class level works
Method[] methods = beanInstance.getClass().getDeclaredMethods();
for (Method method : methods) {
Annotation[] annotations = method.getDeclaredAnnotations();
if (AnnotationUtils.getAnnotation(method, PostConstruct.class) != null) {
log.debug("@PostConstruct annotation found on method {}", method.getName());
method.invoke(beanInstance);
}
}
log.debug("Spring bean reloaded: {}", beanInstance.getClass());
} catch (NoUniqueBeanDefinitionException nbde) {
log.warn("There are several instances of {}, reloading is not yet supported for non-unique beans", typename);
} catch (NoSuchBeanDefinitionException nsbde) {
log.info("Bean {} is not registered yet, creating it", typename);
} catch (Exception e) {
log.warn("Could not hot reload Spring bean!");
e.printStackTrace();
}
} else {
log.trace("This class does not have Spring annotations, it is not considered a Spring Bean");
}
}Example 53
| Project: cta-otp-master File: OTPComponentProviderFactory.java View source code |
/** Perform field injection on all bound instances, in the order they were bound. */
private void injectFields() {
LOG.info("Performing field injection on all bound instances.");
for (Object instance : bindingOrder) {
LOG.debug("Performing field injection on class {}", instance.getClass());
for (Field field : instance.getClass().getDeclaredFields()) {
LOG.debug("Considering field {} for injection", field.getName());
if (field.isAnnotationPresent(Inject.class) || field.isAnnotationPresent(Autowired.class)) {
// since we're still using Spring
Object obj = bindings.get(field.getType());
LOG.debug("Injecting field {} on instance of {}", field.getName(), instance.getClass());
if (obj != null) {
try {
field.setAccessible(true);
field.set(instance, obj);
} catch (Exception ex) {
LOG.error("Failed to perform field injection: {}", ex.toString());
ex.printStackTrace();
}
} else {
LOG.error("Found no binding for {}", field.getType());
}
}
}
}
}Example 54
| Project: ehour-master File: HibernateConfiguration.java View source code |
@Bean(name = "sessionFactory")
@Autowired
public SessionFactory getSessionFactory(DatabaseConfig databaseConfig) throws Exception {
String databaseName = databaseConfig.databaseType.name().toLowerCase();
Properties configProperties = EhourHomeUtil.loadDatabaseProperties(databaseName);
LOGGER.info("Using database type: " + databaseName);
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
if (databaseConfig.databaseType == Database.DERBY) {
EmbeddedConnectionPoolDataSource dataSource = createDerbyDataSource();
sessionFactoryBean.setDataSource(dataSource);
}
List<Resource> mappingResources = getMappingResources(configProperties);
sessionFactoryBean.setMappingLocations(mappingResources.toArray(new Resource[mappingResources.size()]));
sessionFactoryBean.setPackagesToScan(getPackagesToScan());
Properties hibernateProperties = getHibernateProperties(configProperties, databaseConfig);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
beforeFinalizingSessionFactoryBean(sessionFactoryBean);
sessionFactoryBean.afterPropertiesSet();
return sessionFactoryBean.getObject();
}Example 55
| Project: find-master File: IdolConfiguration.java View source code |
@SuppressWarnings("SpringJavaAutowiringInspection")
@Bean
@Autowired
@Primary
public ObjectMapper jacksonObjectMapper(final Jackson2ObjectMapperBuilder builder, final AuthenticationInformationRetriever<?, ?> authenticationInformationRetriever) {
final ObjectMapper mapper = builder.createXmlMapper(false).mixIn(Authentication.class, IdolAuthenticationMixins.class).mixIn(Widget.class, WidgetMixins.class).mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class).mixIn(QueryRestrictions.class, IdolQueryRestrictionsMixin.class).mixIn(IdolQueryRestrictions.class, IdolQueryRestrictionsMixin.class).featuresToEnable(SerializationFeature.INDENT_OUTPUT).build();
mapper.setInjectableValues(new InjectableValues.Std().addValue(AuthenticationInformationRetriever.class, authenticationInformationRetriever));
return mapper;
}Example 56
| Project: head-master File: UiTestCaseBase.java View source code |
@Autowired
@Test(enabled = false)
public void setSelenium(Selenium selenium) {
this.selenium = selenium;
synchronized (UiTestCaseBase.class) {
if (!seleniumServerIsRunning.booleanValue()) {
selenium.start();
selenium.windowFocus();
selenium.windowMaximize();
seleniumServerIsRunning = Boolean.TRUE;
}
}
}Example 57
| Project: jdal-master File: UrlBeanNameUiMapping.java View source code |
/**
* Init th url map parsing {@link UiMapping} annotations
* @param ctx ApplicationContext
*/
@Autowired
public void init(ApplicationContext ctx) {
Map<String, Object> uis = ctx.getBeansWithAnnotation(UiMapping.class);
for (String name : uis.keySet()) {
Object ui = uis.get(name);
if (ui instanceof UI) {
UiMapping ann = AnnotationUtils.findAnnotation(ui.getClass(), UiMapping.class);
if (ann != null) {
if (log.isDebugEnabled())
log.debug("Mapping UI [" + ui.getClass().getName() + "] to request path [" + ann.value() + "]");
this.urlMap.put(ann.value(), name);
}
}
}
}Example 58
| Project: jdonframework-master File: AppContextJdon.java View source code |
/**
* BeanDefinitionRegistryPostProcessor's method
*
* second run: check which spring bean that need injected from Jdon.
*
*/
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
String beanClassName = beanDefinition.getBeanClassName();
try {
Class beanClass = Class.forName(beanClassName);
// large project need using Google Collection's lookup
for (final Field field : ClassUtil.getAllDecaredFields(beanClass)) {
if (field.isAnnotationPresent(Autowired.class)) {
// inject jdon components into spring components with
// AutoWire;
Object o = findBeanClassInJdon(field.getType());
if (o != null) {
neededJdonComponents.put(field.getName(), o);
}
}
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}Example 59
| Project: jersey-master File: AutowiredInjectResolver.java View source code |
@Override
public Object resolve(Injectee injectee) {
AnnotatedElement parent = injectee.getParent();
String beanName = null;
if (parent != null) {
Qualifier an = parent.getAnnotation(Qualifier.class);
if (an != null) {
beanName = an.value();
}
}
boolean required = parent != null ? parent.getAnnotation(Autowired.class).required() : false;
return getBeanFromSpringContext(beanName, injectee, required);
}Example 60
| Project: kaleido-repository-master File: BeanContextPostProcessor.java View source code |
@Override
public Object postProcessBeforeInitialization(final Object beanInstance, final String beanName) throws BeansException {
Set<Field> fields = ReflectionHelper.getAllDeclaredFields(beanInstance.getClass());
for (Field field : fields) {
// @Autowired is injected using spring bean
if (field.isAnnotationPresent(Context.class) && !field.isAnnotationPresent(Autowired.class) && !field.isAnnotationPresent(Inject.class)) {
final Context context = field.getAnnotation(Context.class);
// do field is a runtime context class
if (field.getType().isAssignableFrom(RuntimeContext.class)) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, beanInstance, RuntimeContext.createFrom(context, field.getName(), field.getDeclaringClass()));
} else // does the plugin interface have a provider specify
if (field.getType().isAnnotationPresent(Provider.class)) {
try {
ReflectionUtils.makeAccessible(field);
Object fieldValue = field.get(beanInstance);
if (fieldValue == null) {
// create provider using annotation meta-information
final Provider provideInfo = field.getType().getAnnotation(Provider.class);
final Constructor<? extends ProviderService<?>> providerConstructor = provideInfo.value().getConstructor(Class.class);
final ProviderService<?> fieldProviderInstance = providerConstructor.newInstance(field.getType());
// invoke provides method with Context annotation meta-informations
final Method providesMethod = ReflectionUtils.findMethod(provideInfo.value(), ProviderService.PROVIDES_METHOD, Context.class, String.class, Class.class);
// get the provider result
fieldValue = ReflectionUtils.invokeMethod(providesMethod, fieldProviderInstance, context, field.getName(), field.getType());
// set the field that was not yet injected
ReflectionUtils.setField(field, beanInstance, fieldValue);
}
} catch (IllegalArgumentException e) {
throw new BeanCreationException("Unexpected error during injection", e);
} catch (IllegalAccessException e) {
throw new BeanCreationException("Unexpected error during injection", e);
} catch (SecurityException e) {
throw new BeanCreationException("Unexpected error during injection", e);
} catch (NoSuchMethodException e) {
throw new BeanCreationException("Unexpected error during injection", e);
} catch (InstantiationException e) {
throw new BeanCreationException("Unexpected error during injection", e);
} catch (InvocationTargetException ite) {
throw new BeanCreationException("", ite.getCause() != null ? ite.getCause() : (ite.getTargetException() != null ? ite.getTargetException() : ite));
} finally {
}
}
}
}
return beanInstance;
}Example 61
| Project: libresonic-master File: GlobalSecurityConfig.java View source code |
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
if (settingsService.isLdapEnabled()) {
auth.ldapAuthentication().contextSource().managerDn(settingsService.getLdapManagerDn()).managerPassword(settingsService.getLdapManagerPassword()).url(settingsService.getLdapUrl()).and().userSearchFilter(settingsService.getLdapSearchFilter()).userDetailsContextMapper(libresonicUserDetailsContextMapper);
}
auth.userDetailsService(securityService);
String jwtKey = settingsService.getJWTKey();
if (StringUtils.isBlank(jwtKey)) {
logger.warn("Generating new jwt key");
jwtKey = JWTSecurityService.generateKey();
settingsService.setJWTKey(jwtKey);
settingsService.save();
}
auth.authenticationProvider(new JWTAuthenticationProvider(jwtKey));
}Example 62
| Project: magnificent-mileage-master File: OTPComponentProviderFactory.java View source code |
/** Perform field injection on all bound instances, in the order they were bound. */
private void injectFields() {
LOG.info("Performing field injection on all bound instances.");
for (Object instance : bindingOrder) {
LOG.debug("Performing field injection on class {}", instance.getClass());
for (Field field : instance.getClass().getDeclaredFields()) {
LOG.debug("Considering field {} for injection", field.getName());
if (field.isAnnotationPresent(Inject.class) || field.isAnnotationPresent(Autowired.class)) {
// since we're still using Spring
Object obj = bindings.get(field.getType());
LOG.debug("Injecting field {} on instance of {}", field.getName(), instance.getClass());
if (obj != null) {
try {
field.setAccessible(true);
field.set(instance, obj);
} catch (Exception ex) {
LOG.error("Failed to perform field injection: {}", ex.toString());
ex.printStackTrace();
}
} else {
LOG.error("Found no binding for {}", field.getType());
}
}
}
}
}Example 63
| Project: mifos-head-master File: UiTestCaseBase.java View source code |
@Autowired
@Test(enabled = false)
public void setSelenium(Selenium selenium) {
this.selenium = selenium;
synchronized (UiTestCaseBase.class) {
if (!seleniumServerIsRunning.booleanValue()) {
selenium.start();
selenium.windowFocus();
selenium.windowMaximize();
seleniumServerIsRunning = Boolean.TRUE;
}
}
}Example 64
| Project: Mujina-master File: SAMLConfig.java View source code |
@Bean
@Autowired
public HTTPPostBinding httpPostBinding(ParserPool parserPool, VelocityEngine velocityEngine, @Value("${sp.compare_endpoints}") boolean compareEndpoints) {
HTTPPostEncoder encoder = new HTTPPostEncoder(velocityEngine, "/templates/saml2-post-binding.vm");
HTTPPostDecoder decoder = new HTTPPostDecoder(parserPool);
if (!compareEndpoints) {
decoder.setURIComparator(( uri1, uri2) -> true);
}
return new HTTPPostBinding(parserPool, decoder, encoder);
}Example 65
| Project: neba-master File: ResourceModelMetaData.java View source code |
/**
* @param field must not be <code>null</code>.
* @return whether the field is explicitly excluded from OCM, e.g. via @{@link Unmapped}.
*/
private boolean isUnmapped(Field field) {
final Annotations annotations = annotations(field);
return annotations.contains(Unmapped.class) || // @Inject is an optional dependency, thus using a name constant
annotations.containsName("javax.inject.Inject") || annotations.containsName(Autowired.class.getName()) || annotations.containsName(Resource.class.getName());
}Example 66
| Project: ngrinder-siteminder-sso-master File: SiteMinderFilter.java View source code |
@Autowired
public void setSiteMinderFilterExtension(IConfig config) {
PropertiesWrapper systemProperties = config.getSystemProperties();
userIdHeader = systemProperties.getProperty("ngrinder.sso.header.id", "id");
userNameHeader = systemProperties.getProperty("ngrinder.sso.header.name", "name");
userEmailHeader = systemProperties.getProperty("ngrinder.sso.header.mail", "mail");
userCellPhoneHeader = systemProperties.getProperty("ngrinder.sso.header.cellphone", "mail");
userLocaleHeader = systemProperties.getProperty("ngrinder.sso.header.locale", "locale");
userTimezoneHeader = systemProperties.getProperty("ngrinder.sso.header.timezone", "timezone");
defaultLocale = systemProperties.getProperty("ngrinder.sso.default.locale", "en");
defaultTimezone = systemProperties.getProperty("ngrinder.sso.default.timezone", "Asia/Seoul");
}Example 67
| Project: opennms_dashboard-master File: BeanUtils.java View source code |
/**
* Check that all fields that are marked with @Autowired are not null.
*/
public static <T> void assertAutowiring(T instance) {
for (Field field : instance.getClass().getDeclaredFields()) {
Autowired autowired = field.getAnnotation(Autowired.class);
Resource resource = field.getAnnotation(Resource.class);
if ((autowired != null && autowired.required()) || (resource != null)) {
try {
field.setAccessible(true);
notNull(field.get(instance), "@Autowired/@Resource field " + field.getName() + " cannot be null");
LogUtils.debugf(instance, "%s is not null", field.getName());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Illegal access to @Autowired/@Resource field " + field.getName());
}
}
}
}Example 68
| Project: spring-data-jdbc-ext-master File: ClassicAdvancedDataTypesDao.java View source code |
@Autowired
public void init(DataSource dataSource) {
this.addSqlActorProc = new AddSqlActorProc(dataSource);
this.getSqlActorProc = new GetSqlActorProc(dataSource);
this.addActorProc = new AddActorProc(dataSource);
this.getActorProc = new GetActorProc(dataSource);
this.getActorNamesProc = new GetActorNamesProc(dataSource);
this.deleteActorsProc = new DeleteActorsProc(dataSource);
this.readActorsProc = new ReadActorsProc(dataSource);
this.getActorArrayProc = new GetActorArrayProc(dataSource);
this.saveActorArrayProc = new SaveActorArrayProc(dataSource);
}Example 69
| Project: spring-ide-master File: AddAutowireCompletionProposal.java View source code |
@SuppressWarnings("unchecked")
@Override
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(decl);
ASTRewrite astRewrite = ASTRewrite.create(astRoot.getAST());
AST ast = astRewrite.getAST();
ImportRewrite importRewrite = createImportRewrite(astRoot);
if (params.length == 0) {
createAnnotation(Autowired.class.getCanonicalName(), Autowired.class.getSimpleName(), astRoot, ast, astRewrite, importRewrite, false, null);
} else {
NormalAnnotation autowiredAnnotation = (NormalAnnotation) createAnnotation(Autowired.class.getCanonicalName(), Autowired.class.getSimpleName(), astRoot, ast, astRewrite, importRewrite, true, null);
for (int i = 0; i < params.length; i++) {
switch(params[i]) {
case REQUIRED:
MemberValuePair requiredValue = ast.newMemberValuePair();
requiredValue.setName(ast.newSimpleName("required"));
requiredValue.setValue(ast.newBooleanLiteral(false));
addLinkedPosition(astRewrite.track(requiredValue.getValue()), i == 0, "Autowire");
autowiredAnnotation.values().add(requiredValue);
break;
}
}
}
return astRewrite;
}Example 70
| Project: spring4-showcase-master File: DynamicDeployBeans.java View source code |
@Autowired
public void setApplicationContext(ApplicationContext ctx) {
if (!DefaultListableBeanFactory.class.isAssignableFrom(ctx.getAutowireCapableBeanFactory().getClass())) {
throw new IllegalArgumentException("BeanFactory must be DefaultListableBeanFactory type");
}
this.ctx = ctx;
this.beanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
}Example 71
| Project: unitils-master File: ProfileModule.java View source code |
/**
* The injection of beans doesn't happen automatically anymore when you use {@link SpringBeanByName} or {@link SpringBeanByType}
* @param testObject
*/
public boolean injectBeans(Object testObject) {
//inject beans
boolean everythingOk = true;
for (Field field : testObject.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(Autowired.class)) {
if (!field.isAccessible()) {
//set accessible
field.setAccessible(true);
}
try {
field.set(testObject, ctx.getBean(field.getName()));
} catch (BeansException e) {
LOGGER.error(e.getMessage(), e);
everythingOk = false;
} catch (IllegalArgumentException e) {
LOGGER.error(e.getMessage(), e);
everythingOk = false;
} catch (IllegalAccessException e) {
LOGGER.error(e.getMessage(), e);
everythingOk = false;
}
}
}
if (everythingOk) {
return true;
}
return false;
}Example 72
| Project: WebAPI-master File: DataAccessConfig.java View source code |
@Bean
@Primary
public DataSource primaryDataSource() {
String driver = this.env.getRequiredProperty("datasource.driverClassName");
String url = this.env.getRequiredProperty("datasource.url");
String user = this.env.getRequiredProperty("datasource.username");
String pass = this.env.getRequiredProperty("datasource.password");
boolean autoCommit = false;
//pooling - currently issues with (at least) oracle with use of temp tables and "on commit preserve rows" instead of "on commit delete rows";
//http://forums.ohdsi.org/t/transaction-vs-session-scope-for-global-temp-tables-statements/333/2
/*final PoolConfiguration pc = new org.apache.tomcat.jdbc.pool.PoolProperties();
pc.setDriverClassName(driver);
pc.setUrl(url);
pc.setUsername(user);
pc.setPassword(pass);
pc.setDefaultAutoCommit(autoCommit);*/
//non-pooling
DriverManagerDataSource ds = new DriverManagerDataSource(url, user, pass);
ds.setDriverClassName(driver);
//note autocommit defaults vary across vendors. use provided @Autowired TransactionTemplate
String[] supportedDrivers;
supportedDrivers = new String[] { "org.postgresql.Driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "oracle.jdbc.driver.OracleDriver", "com.amazon.redshift.jdbc41.Driver" };
for (String driverName : supportedDrivers) {
try {
Class.forName(driverName);
System.out.println("driver loaded: " + driverName);
} catch (Exception ex) {
System.out.println("error loading " + driverName + " driver.");
}
}
return ds;
//return new org.apache.tomcat.jdbc.pool.DataSource(pc);
}Example 73
| Project: ethereumj-master File: PrivateNetworkDiscoverySample.java View source code |
@Bean
public BasicSample node() {
return new BasicSample("sampleNode-" + nodeIndex) {
@Autowired
ChannelManager channelManager;
@Autowired
NodeManager nodeManager;
{
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
while (true) {
if (logger != null) {
Thread.sleep(15000);
if (channelManager != null) {
final Collection<Channel> activePeers = channelManager.getActivePeers();
final ArrayList<String> ports = new ArrayList<>();
for (Channel channel : activePeers) {
ports.add(channel.getInetSocketAddress().getHostName() + ":" + channel.getInetSocketAddress().getPort());
}
final Collection<NodeEntry> nodes = nodeManager.getTable().getAllNodes();
final ArrayList<String> nodesString = new ArrayList<>();
for (NodeEntry node : nodes) {
nodesString.add(node.getNode().getHost() + ":" + node.getNode().getPort() + "@" + node.getNode().getHexId().substring(0, 6));
}
logger.info("channelManager.getActivePeers() " + activePeers.size() + " " + Joiner.on(", ").join(ports));
logger.info("nodeManager.getTable().getAllNodes() " + nodesString.size() + " " + Joiner.on(", ").join(nodesString));
} else {
logger.info("Channel manager is null");
}
} else {
System.err.println("Logger is null for " + nodeIndex);
}
}
} catch (Exception e) {
logger.error("Error checking peers count: ", e);
}
}
}).start();
}
@Override
public void onSyncDone() {
logger.info("onSyncDone");
}
};
}Example 74
| Project: ff-master File: AutowiredFF4JBeanPostProcessor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean == null)
return null;
Class<?> beanClass = bean.getClass();
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
// Expect to get annnotation Autowired
if (field.isAnnotationPresent(FF4JProperty.class)) {
autoWiredProperty(bean, field);
} else if (field.isAnnotationPresent(FF4JFeature.class)) {
autoWiredFeature(bean, field);
}
}
return bean;
}Example 75
| Project: ff4j-master File: AutowiredFF4JBeanPostProcessor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean == null)
return null;
Class<?> beanClass = bean.getClass();
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
// Expect to get annnotation Autowired
if (field.isAnnotationPresent(FF4JProperty.class)) {
autoWiredProperty(bean, field);
} else if (field.isAnnotationPresent(FF4JFeature.class)) {
autoWiredFeature(bean, field);
}
}
return bean;
}Example 76
| Project: Fingra.ph_Statistics-Web-master File: FingraphAnthenticationProvider.java View source code |
@Autowired
public void setPasswordEncoder(Object passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
if (passwordEncoder instanceof PasswordEncoder) {
setPasswordEncoder((PasswordEncoder) passwordEncoder);
return;
}
if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder) passwordEncoder;
// password encoder for admin.properties
adminPasswordEncoder = delegate;
setPasswordEncoder(new PasswordEncoder() {
public String encodePassword(String rawPass, Object salt) {
checkSalt(salt);
return delegate.encode(rawPass);
}
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
checkSalt(salt);
return delegate.matches(rawPass, encPass);
}
private void checkSalt(Object salt) {
Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
}
});
return;
}
throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
}Example 77
| Project: light-admin-master File: LightAdminSecurityConfiguration.java View source code |
@Bean
@Autowired
public FilterChainProxy springSecurityFilterChain(Filter filterSecurityInterceptor, Filter authenticationFilter, Filter rememberMeAuthenticationFilter, Filter logoutFilter, Filter exceptionTranslationFilter, Filter securityContextPersistenceFilter) {
List<SecurityFilterChain> filterChains = newArrayList();
for (String pattern : PUBLIC_RESOURCES) {
filterChains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher(applicationUrl(pattern))));
}
filterChains.add(new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, securityContextPersistenceFilter, exceptionTranslationFilter, logoutFilter, authenticationFilter, rememberMeAuthenticationFilter, filterSecurityInterceptor));
return new FilterChainProxy(filterChains);
}Example 78
| Project: OpenConext-teams-master File: Application.java View source code |
@Autowired
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(Environment environment, PersonRepository personRepository, @Value("${teamsURL}") String teamsURL, @Value("${displayExternalTeams}") Boolean displayExternalTeams, @Value("${displayExternalTeamMembers}") Boolean displayExternalTeamMembers, @Value("${displayAddExternalGroupToTeam}") Boolean displayAddExternalGroupToTeam, @Value("${application.version}") String applicationVersion, @Value("${voot.api.user}") String vootApiUser, @Value("${voot.api.password}") String vootApiPassword, ResourceLoader resourceLoader) throws Exception {
List<HandlerInterceptor> interceptors = new ArrayList<>();
String commitId = gitCommitId(resourceLoader, environment);
interceptors.add(new FeatureInterceptor(displayExternalTeams, displayExternalTeamMembers, displayAddExternalGroupToTeam, commitId, applicationVersion));
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
interceptors.add(localeChangeInterceptor);
if (environment.acceptsProfiles(DEV_PROFILE_NAME)) {
LOG.debug("Using mock shibboleth");
interceptors.add(new MockLoginInterceptor(teamsURL, personRepository));
} else {
interceptors.add(new LoginInterceptor(teamsURL, personRepository));
}
interceptors.add(new VootApiSecurityFilter(vootApiUser, vootApiPassword));
return new SpringMvcConfiguration(interceptors);
}Example 79
| Project: openmrs-module-reporting-master File: BaseImplementerConfiguredDefinitionLibrary.java View source code |
private void loadDefinitions() {
Map<String, T> newDefinitions = new HashMap<String, T>();
List<LibraryDefinitionSummary> newSummaries = new ArrayList<LibraryDefinitionSummary>();
ReportingSerializer serializer;
if (serializationService != null) {
serializer = (ReportingSerializer) serializationService.getSerializer(ReportingSerializer.class);
} else {
// this branch is only for tests where serializationService isn't available
try {
serializer = new ReportingSerializer();
} catch (SerializationException e) {
serializer = null;
}
}
if (directory.exists() && directory.isDirectory()) {
for (File file : directory.listFiles()) {
String filename = file.getName();
String definitionName = filename.substring(0, filename.lastIndexOf('.'));
String key = getKeyPrefix() + definitionName;
try {
log.info("Loading " + file.getAbsolutePath());
Definition definition = null;
if (filename.endsWith(".reportingserializerxml")) {
try {
definition = serializer.deserialize(OpenmrsUtil.getFileAsString(file), Definition.class);
} catch (SerializationException ex) {
log.warn("Invalid serialized definition at " + libraryNameSuffix + " in " + file.getAbsolutePath(), ex);
}
} else if (filename.endsWith(".groovy")) {
definition = (Definition) new GroovyHelper().parseClassFromFileAndNewInstance(file);
autowireCapableBeanFactory.autowireBean(definition);
// this only handles @Autowired, not @PostConstruct. To handle that we'd need to also call
// autowireCapableBeanFactory.initializeBean(definition, "bean name");
// (but I'm not sure if this is needed, and I'm not sure what to name the bean)
} else if (filename.endsWith(".sql")) {
String sql = OpenmrsUtil.getFileAsString(file);
definition = sqlDefinition(sql);
} else {
log.warn("Don't know how to handle " + file.getAbsolutePath() + " based on file extension");
}
if (definition != null) {
if (definition.getName() == null) {
definition.setName(key + ".name");
}
if (definition.getDescription() == null) {
definition.setDescription(key + ".description");
}
newDefinitions.put(key, (T) definition);
newSummaries.add(summaryFor(key, definition));
}
} catch (IOException ex) {
log.warn("Error reading " + file.getAbsolutePath(), ex);
}
}
}
this.definitions = newDefinitions;
this.summaries = newSummaries;
}Example 80
| Project: spring-configuration-validation-processor-master File: SpringConfigurationValidationProcessor.java View source code |
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.messager = processingEnv.getMessager();
this.typeUtils = processingEnv.getTypeUtils();
this.elementUtils = processingEnv.getElementUtils();
this.autowiredTypeElement = this.elementUtils.getTypeElement("org.springframework.beans.factory.annotation.Autowired");
this.beanTypeElement = this.elementUtils.getTypeElement("org.springframework.context.annotation.Bean");
this.bfppTypeElement = this.elementUtils.getTypeElement("org.springframework.beans.factory.config.BeanFactoryPostProcessor");
this.configurationTypeElement = this.elementUtils.getTypeElement("org.springframework.context.annotation.Configuration");
}Example 81
| Project: spring-gemfire-examples-master File: SpringJavaBasedContainerGemFireConfiguration.java View source code |
/*
NOTE need to qualify the RegionAttributes bean definition reference since GemFire's
com.gemstone.gemfire.internal.cache.AbstractRegion class "implements" RegionAttributes (face-palm),
which led Spring to the following Exception...
java.lang.IllegalStateException: Failed to load ApplicationContext ...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'ExamplePartition' defined in class org.spring.data.gemfire.config.GemFireConfiguration:
Unsatisfied dependency expressed through constructor argument with index 1 of type [com.gemstone.gemfire.cache.RegionAttributes]:
No qualifying bean of type [com.gemstone.gemfire.cache.RegionAttributes] is defined:
expected single matching bean but found 2: ExampleLocal,defaultRegionAttributes;
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type [com.gemstone.gemfire.cache.RegionAttributes] is defined:
expected single matching bean but found 2: ExampleLocal,defaultRegionAttributes
*/
@Bean(name = "ExamplePartition")
@Autowired
public PartitionedRegionFactoryBean<Object, Object> examplePartitionRegion(Cache gemfireCache, @Qualifier("partitionRegionAttributes") RegionAttributes<Object, Object> regionAttributes) throws Exception {
PartitionedRegionFactoryBean<Object, Object> examplePartitionRegion = new PartitionedRegionFactoryBean<Object, Object>();
examplePartitionRegion.setAttributes(regionAttributes);
examplePartitionRegion.setCache(gemfireCache);
examplePartitionRegion.setName("ExamplePartitionRegion");
examplePartitionRegion.setPersistent(false);
return examplePartitionRegion;
}Example 82
| Project: spring-loaded-spring-plugin-master File: ReloadPlugin.java View source code |
@Override
public synchronized Object call() throws Exception {
Set<ToReloadBean> toReloadBeansCopy = new HashSet<>(toReloadBeans);
toReloadBeans = new HashSet<>();
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
List<ToReloadBean> newSpringBeans = new ArrayList<>();
List<ToReloadBean> existingSpringBeans = new ArrayList<>();
//1) Split between new/existing beans
for (ToReloadBean toReloadBean : toReloadBeansCopy) {
Annotation annotation = getSpringClassAnnotation(toReloadBean.getClazz());
if (annotation != null) {
String beanName = constructBeanName(annotation, toReloadBean.getClazz());
RootBeanDefinition beanDefinition = null;
try {
beanFactory.getBeanDefinition(beanName);
} catch (NoSuchBeanDefinitionException e) {
log.error(e.getMessage(), e);
}
if (beanDefinition == null) {
newSpringBeans.add(toReloadBean);
} else {
existingSpringBeans.add(toReloadBean);
}
}
}
//2) Declare new beans prior to instanciation for cross bean references
for (ToReloadBean toReloadBean : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(toReloadBean.getClazz());
String beanName = constructBeanName(annotation, toReloadBean.getClazz());
String scope = getScope(toReloadBean.getClazz());
RootBeanDefinition bd = new RootBeanDefinition(toReloadBean.getClazz(), AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
bd.setScope(scope);
beanFactory.registerBeanDefinition(beanName, bd);
}
//3) Instanciate new beans
for (ToReloadBean toReloadBean : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(toReloadBean.getClazz());
String beanName = constructBeanName(annotation, toReloadBean.getClazz());
try {
beanFactory.getBean(beanName);
} catch (BeansException e) {
log.error(e.getMessage(), e);
toReloadBeans.add(toReloadBean);
}
}
//4) Resolve deps for existing beans
for (ToReloadBean toReloadBean : existingSpringBeans) {
Object beanInstance = applicationContext.getBean(toReloadBean.getClazz());
// We only support autowiring on fields
log.debug("Existing bean, autowiring fields");
if (AopUtils.isCglibProxy(beanInstance)) {
log.trace("This is a CGLIB proxy, getting the real object");
beanInstance = ((Advised) beanInstance).getTargetSource().getTarget();
} else if (AopUtils.isJdkDynamicProxy(beanInstance)) {
log.trace("This is a JDK proxy, getting the real object");
beanInstance = ((Advised) beanInstance).getTargetSource().getTarget();
}
Field[] fields = beanInstance.getClass().getDeclaredFields();
for (Field field : fields) {
if (AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
log.debug("@Inject annotation found on field {}", field.getName());
Object beanToInject = applicationContext.getBean(field.getType());
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, beanInstance, beanToInject);
}
}
}
return null;
}Example 83
| Project: spring-security-javaconfig-master File: WebSecurityConfiguration.java View source code |
/**
* Sets the {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>} instances used to create the web configuration.
*
* @param webSecurityConfigurers the {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>} instances used to create the web configuration
* @throws Exception
*/
@Autowired(required = false)
public void setFilterChainProxySecurityConfigurer(List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers) throws Exception {
Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);
Integer previousOrder = null;
for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {
Integer order = AnnotationAwareOrderComparator.lookupOrder(config);
if (previousOrder != null && previousOrder.equals(order)) {
throw new IllegalStateException("@Order on WebSecurityConfigurers must be unique. Order of " + order + " was already used, so it cannot be used on " + config + " too.");
}
previousOrder = order;
}
for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {
webSecurity.apply(webSecurityConfigurer);
}
this.webSecurityConfigurers = webSecurityConfigurers;
}Example 84
| Project: spring-security-master File: WebSecurityConfiguration.java View source code |
/**
* Sets the {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>}
* instances used to create the web configuration.
*
* @param objectPostProcessor the {@link ObjectPostProcessor} used to create a
* {@link WebSecurity} instance
* @param webSecurityConfigurers the
* {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>} instances used to
* create the web configuration
* @throws Exception
*/
@Autowired(required = false)
public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor, @Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers) throws Exception {
webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));
if (debugEnabled != null) {
webSecurity.debug(debugEnabled);
}
Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);
Integer previousOrder = null;
Object previousConfig = null;
for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {
Integer order = AnnotationAwareOrderComparator.lookupOrder(config);
if (previousOrder != null && previousOrder.equals(order)) {
throw new IllegalStateException("@Order on WebSecurityConfigurers must be unique. Order of " + order + " was already used on " + previousConfig + ", so it cannot be used on " + config + " too.");
}
previousOrder = order;
previousConfig = config;
}
for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {
webSecurity.apply(webSecurityConfigurer);
}
this.webSecurityConfigurers = webSecurityConfigurers;
}Example 85
| Project: thingsboard-master File: ThingsboardSecurityConfiguration.java View source code |
@Bean
@ConditionalOnMissingBean(CorsFilter.class)
public CorsFilter corsFilter(@Autowired MvcCorsProperties mvcCorsProperties) {
if (mvcCorsProperties.getMappings().size() == 0) {
return new CorsFilter(new UrlBasedCorsConfigurationSource());
} else {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.setCorsConfigurations(mvcCorsProperties.getMappings());
return new CorsFilter(source);
}
}Example 86
| Project: user-master File: ToolBase.java View source code |
@Autowired
public void setProperties(Properties properties) {
this.properties = properties;
logger.info("Properties set: \n" + " cassandra.url: {}\n" + " cassandra.datacenter.local: {}\n" + " cassandra.username: {}\n" + " cassandra.password: {}\n" + " cassandra.keyspace.strategy: {}\n" + " cassandra.keyspace.application: {}\n" + " cassandra.lock.keyspace: {}\n" + " cassandra.keyspace.replication: {}\n" + " cassandra.connections: {}\n" + " usergrid.notifications.listener.run: {}\n" + " usergrid.push.worker_count: {}\n" + " usergrid.scheduler.enabled: {}\n", properties.get("cassandra.url"), properties.get("cassandra.datacenter.local"), properties.get("cassandra.username"), properties.get("cassandra.password"), properties.get("cassandra.keyspace.strategy"), properties.get("cassandra.keyspace.application"), properties.get("cassandra.lock.keyspace"), properties.get("cassandra.keyspace.replication"), properties.get("cassandra.connections"), properties.get("usergrid.notifications.listener.run"), properties.get("usergrid.push.worker_count"), properties.get("usergrid.scheduler.enabled"));
}Example 87
| Project: usergrid-master File: ToolBase.java View source code |
@Autowired
public void setProperties(Properties properties) {
this.properties = properties;
logger.info("Properties set: \n" + " cassandra.url: {}\n" + " cassandra.datacenter.local: {}\n" + " cassandra.username: {}\n" + " cassandra.password: {}\n" + " cassandra.keyspace.strategy: {}\n" + " cassandra.keyspace.application: {}\n" + " cassandra.lock.keyspace: {}\n" + " cassandra.keyspace.replication: {}\n" + " cassandra.connections: {}\n" + " usergrid.notifications.listener.run: {}\n" + " usergrid.push.worker_count: {}\n" + " usergrid.scheduler.enabled: {}\n", properties.get("cassandra.url"), properties.get("cassandra.datacenter.local"), properties.get("cassandra.username"), properties.get("cassandra.password"), properties.get("cassandra.keyspace.strategy"), properties.get("cassandra.keyspace.application"), properties.get("cassandra.lock.keyspace"), properties.get("cassandra.keyspace.replication"), properties.get("cassandra.connections"), properties.get("usergrid.notifications.listener.run"), properties.get("usergrid.push.worker_count"), properties.get("usergrid.scheduler.enabled"));
}Example 88
| Project: tianti-master File: GenCodeUtil.java View source code |
/**
* 创建service类
* @param c实体类
* @param commonPackage 基础包:如com.jeff.tianti.info
* @throws IOException
*/
public static void createServiceClass(Class c, String commonPackage, String author) throws IOException {
String cName = c.getName();
String servicePath = "";
if (author == null || author.equals("")) {
author = "Administrator";
}
if (commonPackage != null && !commonPackage.equals("")) {
servicePath = commonPackage.replace(".", "/");
String fileName = System.getProperty("user.dir") + "/src/main/java/" + servicePath + "/service" + "/" + getLastChar(cName) + "Service.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package " + commonPackage + ".service" + ";" + RT_2 + "import " + commonPackage + ".entity" + "." + getLastChar(cName) + ";" + RT_1 + "import " + commonPackage + ".dao" + "." + getLastChar(cName) + "Dao;" + RT_1 + "import " + commonPackage + ".dto" + "." + getLastChar(cName) + "QueryDTO;" + RT_1 + "import com.jeff.tianti.common.service.CommonService;" + RT_1 + "import com.jeff.tianti.common.entity.PageModel;" + RT_1 + "import org.springframework.stereotype.Service;" + RT_1 + "import java.util.List;" + RT_1 + "import org.springframework.beans.factory.annotation.Autowired;" + RT_1 + "/**" + RT_1 + BLANK_1 + "*" + BLANK_1 + ANNOTATION_AUTHOR_PARAMTER + author + RT_1 + BLANK_1 + "*" + BLANK_1 + ANNOTATION_DESC + getLastChar(cName) + "Serviceç±»" + BLANK_1 + RT_1 + BLANK_1 + "*" + BLANK_1 + ANNOTATION_DATE + getDate() + RT_1 + BLANK_1 + "*/" + RT_1 + "@Service" + RT_1 + "public class " + getLastChar(cName) + "Service extends CommonService< " + getLastChar(cName) + ",String > {" + RT_2 + " @Autowired" + RT_1 + " private " + getLastChar(cName) + "Dao " + getFirstLowercase(cName) + "Dao;" + RT_2 + " @Autowired" + RT_1 + " public void set" + getLastChar(cName) + "Dao(" + getLastChar(cName) + "Dao " + getFirstLowercase(cName) + "Dao){" + RT_1 + " super.setCommonDao(" + getFirstLowercase(cName) + "Dao);" + RT_1 + " }" + RT_2 + " public PageModel<" + getLastChar(cName) + "> query" + getLastChar(cName) + "Page(" + getLastChar(cName) + "QueryDTO " + getFirstLowercase(cName) + "QueryDTO){" + RT_1 + " return this." + getFirstLowercase(cName) + "Dao.query" + getLastChar(cName) + "Page(" + getFirstLowercase(cName) + "QueryDTO);" + RT_1 + " }" + RT_2 + " public List<" + getLastChar(cName) + "> query" + getLastChar(cName) + "List(" + getLastChar(cName) + "QueryDTO " + getFirstLowercase(cName) + "QueryDTO){" + RT_1 + " return this." + getFirstLowercase(cName) + "Dao.query" + getLastChar(cName) + "List(" + getFirstLowercase(cName) + "QueryDTO);" + RT_1 + " }" + RT_1 + RT_2 + "}");
fw.flush();
fw.close();
showInfo(fileName);
} else {
System.out.println("创建Service接å?£å¤±è´¥ï¼ŒåŽŸå› æ˜¯commonPackage为空ï¼?");
}
}Example 89
| Project: abiquo-master File: EnterpriseDAO.java View source code |
/**
* Gets the repository usage for the given enterprise.
*
* @param idEnterprise The enterprise being checked.
* @return The amount of used repository space.
* @throws PersistenceException If an error occurs.
*/
private Long getRepositoryUsage(final Integer idEnterprise) {
return 0l;
// @Autowired
// DatacenterRep datacenterRep;
//
// @Autowired
// RemoteServiceDAO remoteServiceDao;
// long repoUsed = 0L;
//
// final List<Datacenter> datacenters = datacenterRep.findAll();
//
// for (final Datacenter dc : datacenters)
// {
//
// try
// {
// final String amUrl =
// remoteServiceDao.getRemoteServiceUri(dc, RemoteServiceType.APPLIANCE_MANAGER);
//
// final EnterpriseRepositoryDto repoData =
// amStub.getRepository(am.getUri(), String.valueOf(idEnterprise));
//
// repoUsed += repoData.getRepositoryEnterpriseUsedMb();
//
// }
// catch (Exception e) // am not defined on this datacenter
// {
//
// }
// }
//
// return repoUsed;
}Example 90
| Project: apmrouter-master File: UDPAgentOperationRouter.java View source code |
/**
* Sets the agent request handlers
* @param agentRequestHandlers a collection of agent request handlers
*/
@Autowired(required = true)
public void setAgentRequestHandlers(Collection<AgentRequestHandler> agentRequestHandlers) {
for (AgentRequestHandler arh : agentRequestHandlers) {
for (OpCode soc : arh.getHandledOpCodes()) {
handlers.put(soc, arh);
info("Added AgentRequestHandler [", arh.getClass().getSimpleName(), "] for Op [", soc, "]");
}
}
handlers.put(OpCode.WHO_RESPONSE, this);
handlers.put(OpCode.BYE, this);
handlers.put(OpCode.HELLO, this);
handlers.put(OpCode.HELLO_CONFIRM, this);
handlers.put(OpCode.JMX_MBS_INQUIRY_RESPONSE, this);
}Example 91
| Project: citrus-master File: SpringExtUtilTests.java View source code |
@Test
public void autowireAndInitialize() throws Exception {
ApplicationContext context = new XmlApplicationContext(new FileSystemResource(new File(srcdir, "beans.xml")));
class Bean implements BeanNameAware, ApplicationContextAware, InitializingBean {
@Autowired
private com.alibaba.citrus.springext.support.context.MyClass myClass;
private String beanName;
private ApplicationContext context;
private boolean inited;
public void setBeanName(String name) {
this.beanName = name;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public void afterPropertiesSet() throws Exception {
this.inited = true;
}
}
Bean bean = new Bean();
assertSame(bean, SpringExtUtil.autowireAndInitialize(bean, context, AutowireCapableBeanFactory.AUTOWIRE_NO, "myname"));
assertNotNull(bean.myClass);
assertEquals("myname", bean.beanName);
assertSame(context, bean.context);
assertTrue(bean.inited);
}Example 92
| Project: hdiv-archive-master File: SimpleJdbcClinic.java View source code |
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.insertOwner = new SimpleJdbcInsert(dataSource).withTableName("owners").usingGeneratedKeyColumns("id");
this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");
this.insertVisit = new SimpleJdbcInsert(dataSource).withTableName("visits").usingGeneratedKeyColumns("id");
}Example 93
| Project: JavascriptGame-master File: SpringReloader.java View source code |
private void start(List<Class> newSpringBeans, List<Class> existingSpringBeans) {
try {
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
//1) Split between new/existing beans
for (Class toReloadBean : toReloadBeans) {
log.trace("Hot reloading Spring bean: {}", toReloadBean.getName());
Annotation annotation = getSpringClassAnnotation(toReloadBean);
String beanName = constructBeanName(annotation, toReloadBean);
if (!beanFactory.containsBeanDefinition(beanName)) {
newSpringBeans.add(toReloadBean);
// If so add this dependent class to the newSpringBeans list
if (newToWaitFromBeans.size() > 0) {
newSpringBeans.addAll(newToWaitFromBeans);
newToWaitFromBeans.clear();
}
} else {
existingSpringBeans.add(toReloadBean);
if (existingToWaitFromBeans.containsKey(toReloadBean.getName())) {
existingSpringBeans.add(existingToWaitFromBeans.get(toReloadBean.getName()));
existingToWaitFromBeans.remove(toReloadBean.getName());
}
}
}
//2) Declare new beans prior to instanciation for cross bean references
for (Class clazz : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(clazz);
String beanName = constructBeanName(annotation, clazz);
String scope = getScope(clazz);
RootBeanDefinition bd = new RootBeanDefinition(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
bd.setScope(scope);
beanFactory.registerBeanDefinition(beanName, bd);
}
//3) Instanciate new beans
for (Class clazz : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(clazz);
String beanName = constructBeanName(annotation, clazz);
try {
// This is a spring data interface
if (ClassUtils.isAssignable(clazz, org.springframework.data.repository.Repository.class)) {
final Object repository = jpaRepositoryFactory.getRepository(clazz);
beanFactory.registerSingleton(beanName, repository);
} else {
beanFactory.getBean(beanName);
}
processListener(clazz, true);
toReloadBeans.remove(clazz);
log.info("JHipster reload - New Spring bean '{}' has been reloaded.", clazz);
} catch (Exception e) {
log.trace("The Spring bean can't be loaded at this time. Keep it to reload it later", e);
beanFactory.removeBeanDefinition(beanName);
newToWaitFromBeans.add(clazz);
toReloadBeans.remove(clazz);
}
}
//4) Resolve dependencies for existing beans
for (Class clazz : existingSpringBeans) {
Object beanInstance = applicationContext.getBean(clazz);
log.trace("Existing bean, autowiring fields");
if (AopUtils.isCglibProxy(beanInstance)) {
log.trace("This is a CGLIB proxy, getting the real object");
addAdvisorIfNeeded(clazz, beanInstance);
final Advised advised = (Advised) beanInstance;
beanInstance = advised.getTargetSource().getTarget();
} else if (AopUtils.isJdkDynamicProxy(beanInstance)) {
log.trace("This is a JDK proxy, getting the real object");
addAdvisorIfNeeded(clazz, beanInstance);
final Advised advised = (Advised) beanInstance;
beanInstance = advised.getTargetSource().getTarget();
} else {
log.trace("This is a normal Java object");
}
boolean failedToUpdate = false;
Field[] fields = beanInstance.getClass().getDeclaredFields();
for (Field field : fields) {
if (AnnotationUtils.getAnnotation(field, Inject.class) != null || AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
log.trace("@Inject/@Autowired annotation found on field {}", field.getName());
ReflectionUtils.makeAccessible(field);
if (ReflectionUtils.getField(field, beanInstance) != null) {
log.trace("Field is already injected, not doing anything");
} else {
log.trace("Field is null, injecting a Spring bean");
try {
Object beanToInject = applicationContext.getBean(field.getType());
ReflectionUtils.setField(field, beanInstance, beanToInject);
} catch (NoSuchBeanDefinitionException bsbde) {
log.debug("JHipster reload - Spring bean '{}' does not exist, " + "wait until this class will be available.", field.getType());
failedToUpdate = true;
existingToWaitFromBeans.put(field.getType().getName(), clazz);
}
}
}
}
toReloadBeans.remove(clazz);
if (!failedToUpdate) {
processListener(clazz, false);
}
log.info("JHipster reload - Existing Spring bean '{}' has been reloaded.", clazz);
}
for (SpringReloadListener springReloadListener : springReloadListeners) {
springReloadListener.execute();
}
} catch (Exception e) {
log.warn("Could not hot reload Spring bean!", e);
}
}Example 94
| Project: kmf-content-api-master File: AbstractContentHandlerServlet.java View source code |
@Override
public void init() throws ServletException {
super.init();
// Recover application context associated to this servlet in this
// context
AnnotationConfigApplicationContext thisServletContext = KurentoApplicationContextUtils.getKurentoServletApplicationContext(this.getClass(), this.getServletName());
// create one
if (thisServletContext == null) {
// Locate the handler class associated to this servlet
String handlerClassName = this.getInitParameter(ContentApiWebApplicationInitializer.HANDLER_CLASS_PARAM_NAME);
if (handlerClassName == null || handlerClassName.equals("")) {
String message = "Cannot find handler class associated to handler servlet with name " + this.getServletConfig().getServletName() + " and class " + this.getClass().getName();
getLogger().error(message);
throw new ServletException(message);
}
// Create application context for this servlet containing the
// handler
thisServletContext = KurentoApplicationContextUtils.createKurentoHandlerServletApplicationContext(this.getClass(), this.getServletName(), this.getServletContext(), handlerClassName);
// useRedirectStrategy = getUseRedirectStrategy(handlerClass);
try {
handlerClass = Class.forName(handlerClassName);
} catch (ClassNotFoundException e) {
String message = "Cannot recover class " + handlerClass + " on classpath";
getLogger().error(message);
throw new ServletException(message);
}
useControlProtocol = getUseJsonControlProtocol(handlerClass);
}
// Make this servlet to receive beans to resolve the @Autowired present
// on it
KurentoApplicationContextUtils.processInjectionBasedOnApplicationContext(this, thisServletContext);
if (useControlProtocol) {
contentSessionManager = (ContentSessionManager) KurentoApplicationContextUtils.getBean("contentSessionManager");
}
}Example 95
| Project: kurento-media-framework-master File: AbstractContentHandlerServlet.java View source code |
@Override
public void init() throws ServletException {
super.init();
// Recover application context associated to this servlet in this
// context
AnnotationConfigApplicationContext thisServletContext = KurentoApplicationContextUtils.getKurentoServletApplicationContext(this.getClass(), this.getServletName());
// create one
if (thisServletContext == null) {
// Locate the handler class associated to this servlet
String handlerClassName = this.getInitParameter(ContentApiWebApplicationInitializer.HANDLER_CLASS_PARAM_NAME);
if (handlerClassName == null || handlerClassName.equals("")) {
String message = "Cannot find handler class associated to handler servlet with name " + this.getServletConfig().getServletName() + " and class " + this.getClass().getName();
getLogger().error(message);
throw new ServletException(message);
}
// Create application context for this servlet containing the
// handler
thisServletContext = KurentoApplicationContextUtils.createKurentoHandlerServletApplicationContext(this.getClass(), this.getServletName(), this.getServletContext(), handlerClassName);
// useRedirectStrategy = getUseRedirectStrategy(handlerClass);
try {
handlerClass = Class.forName(handlerClassName);
} catch (ClassNotFoundException e) {
String message = "Cannot recover class " + handlerClass + " on classpath";
getLogger().error(message);
throw new ServletException(message);
}
useControlProtocol = getUseJsonControlProtocol(handlerClass);
}
// Make this servlet to receive beans to resolve the @Autowired present
// on it
KurentoApplicationContextUtils.processInjectionBasedOnApplicationContext(this, thisServletContext);
if (useControlProtocol) {
contentSessionManager = (ContentSessionManager) KurentoApplicationContextUtils.getBean("contentSessionManager");
}
}Example 96
| Project: parkingfriends-master File: SpringReloader.java View source code |
private void start(List<Class> newSpringBeans, List<Class> existingSpringBeans) {
try {
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
//1) Split between new/existing beans
for (Class toReloadBean : toReloadBeans) {
log.trace("Hot reloading Spring bean: {}", toReloadBean.getName());
Annotation annotation = getSpringClassAnnotation(toReloadBean);
String beanName = constructBeanName(annotation, toReloadBean);
if (!beanFactory.containsBeanDefinition(beanName)) {
newSpringBeans.add(toReloadBean);
// If so add this dependent class to the newSpringBeans list
if (newToWaitFromBeans.size() > 0) {
newSpringBeans.addAll(newToWaitFromBeans);
newToWaitFromBeans.clear();
}
} else {
existingSpringBeans.add(toReloadBean);
if (existingToWaitFromBeans.containsKey(toReloadBean.getName())) {
existingSpringBeans.add(existingToWaitFromBeans.get(toReloadBean.getName()));
existingToWaitFromBeans.remove(toReloadBean.getName());
}
}
}
//2) Declare new beans prior to instanciation for cross bean references
for (Class clazz : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(clazz);
String beanName = constructBeanName(annotation, clazz);
String scope = getScope(clazz);
RootBeanDefinition bd = new RootBeanDefinition(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
bd.setScope(scope);
beanFactory.registerBeanDefinition(beanName, bd);
}
//3) Instanciate new beans
for (Class clazz : newSpringBeans) {
Annotation annotation = getSpringClassAnnotation(clazz);
String beanName = constructBeanName(annotation, clazz);
try {
// This is a spring data interface
if (ClassUtils.isAssignable(clazz, org.springframework.data.repository.Repository.class)) {
final Object repository = jpaRepositoryFactory.getRepository(clazz);
beanFactory.registerSingleton(beanName, repository);
} else {
beanFactory.getBean(beanName);
}
processListener(clazz, true);
toReloadBeans.remove(clazz);
log.info("JHipster reload - New Spring bean '{}' has been reloaded.", clazz);
} catch (Exception e) {
log.trace("The Spring bean can't be loaded at this time. Keep it to reload it later", e);
beanFactory.removeBeanDefinition(beanName);
newToWaitFromBeans.add(clazz);
toReloadBeans.remove(clazz);
}
}
//4) Resolve dependencies for existing beans
for (Class clazz : existingSpringBeans) {
Object beanInstance = applicationContext.getBean(clazz);
log.trace("Existing bean, autowiring fields");
if (AopUtils.isCglibProxy(beanInstance)) {
log.trace("This is a CGLIB proxy, getting the real object");
addAdvisorIfNeeded(clazz, beanInstance);
final Advised advised = (Advised) beanInstance;
beanInstance = advised.getTargetSource().getTarget();
} else if (AopUtils.isJdkDynamicProxy(beanInstance)) {
log.trace("This is a JDK proxy, getting the real object");
addAdvisorIfNeeded(clazz, beanInstance);
final Advised advised = (Advised) beanInstance;
beanInstance = advised.getTargetSource().getTarget();
} else {
log.trace("This is a normal Java object");
}
boolean failedToUpdate = false;
Field[] fields = beanInstance.getClass().getDeclaredFields();
for (Field field : fields) {
if (AnnotationUtils.getAnnotation(field, Inject.class) != null || AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
log.trace("@Inject/@Autowired annotation found on field {}", field.getName());
ReflectionUtils.makeAccessible(field);
if (ReflectionUtils.getField(field, beanInstance) != null) {
log.trace("Field is already injected, not doing anything");
} else {
log.trace("Field is null, injecting a Spring bean");
try {
Object beanToInject = applicationContext.getBean(field.getType());
ReflectionUtils.setField(field, beanInstance, beanToInject);
} catch (NoSuchBeanDefinitionException bsbde) {
log.debug("JHipster reload - Spring bean '{}' does not exist, " + "wait until this class will be available.", field.getType());
failedToUpdate = true;
existingToWaitFromBeans.put(field.getType().getName(), clazz);
}
}
}
}
toReloadBeans.remove(clazz);
if (!failedToUpdate) {
processListener(clazz, false);
}
log.info("JHipster reload - Existing Spring bean '{}' has been reloaded.", clazz);
}
for (SpringReloadListener springReloadListener : springReloadListeners) {
springReloadListener.execute();
}
} catch (Exception e) {
log.warn("Could not hot reload Spring bean!", e);
}
}Example 97
| Project: phoenix.platform-master File: ProjectController.java View source code |
@RequestMapping("/deploy")
public String projectDeploy(String id) {
UserDetail userDetail = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String ownerId = userDetail.getId();
String projectId = id;
File rootDir = new File(servletContext.getRealPath("/deploy"), id + "/" + ownerId);
rootDir.mkdirs();
File srcOutputDir = new File(rootDir, "src");
JDTUtils jdtUtils = new JDTUtils(srcOutputDir);
//附件拷�
List<Attachment> attachList = attachmentMapper.getByBelongId(projectId);
if (CollectionUtils.isNotEmpty(attachList)) {
for (Attachment attach : attachList) {
String name = attach.getFileName();
if (name.endsWith(".java")) {
String pkgPath = attach.getRemark();
pkgPath = StringUtils.isBlank(pkgPath) ? "" : pkgPath.trim();
pkgPath = pkgPath.replace(".", "/");
try {
FileUtils.copyFile(new File(attach.getRelativePath(), name), new File(srcOutputDir, pkgPath + "/" + name));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//å…ƒç´ å®šä½?文件部署
List<PageInfo> pageInfoList = pageInfoMapper.getAllWithContentByProjectId(projectId);
if (CollectionUtils.isNotEmpty(pageInfoList)) {
for (PageInfo pageInfo : pageInfoList) {
String content = pageInfo.getContent();
File autotestFile = new File(rootDir, pageInfo.getName() + ".xml");
try {
FileUtils.writeStringToFile(autotestFile, content, "UTF-8");
//生æˆ?Javaæº?ç ?
codeGenerator.generate(autotestFile.toString(), srcOutputDir.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
//编译Javaæº?ç ?
List<File> result = jdtUtils.compileAllFile();
try {
AutoTestClassloader cla = new AutoTestClassloader(new URL[] { srcOutputDir.toURI().toURL() }, Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(cla);
String rootPath = srcOutputDir.getAbsolutePath();
for (File javaSrcFile : result) {
String absPath = javaSrcFile.getAbsolutePath();
String clsName = absPath.replace(rootPath, "").replace("/", "\\").replace("\\", ".").replace(".java", "");
clsName = clsName.substring(1);
Class<?> target = cla.loadClass(clsName);
BeanDefinitionRegistry reg = (BeanDefinitionRegistry) ((ConfigurableApplicationContext) applicationContext.getParent()).getBeanFactory();
BeanDefinitionBuilder beanDef = BeanDefinitionBuilder.genericBeanDefinition(target);
AbstractBeanDefinition bean = beanDef.getBeanDefinition();
reg.registerBeanDefinition(target.getName(), bean);
Object targetObj = applicationContext.getBean(target.getName());
for (Field field : target.getDeclaredFields()) {
try {
Object fieldObj = applicationContext.getBean(field.getType());
field.setAccessible(true);
field.set(targetObj, fieldObj);
;
} catch (IllegalAccessExceptionIllegalArgumentException | e) {
e.printStackTrace();
} catch (NoSuchBeanDefinitionException e) {
}
if (field.getAnnotation(Autowired.class) != null) {
}
}
}
} catch (MalformedURLExceptionClassNotFoundException | e) {
e.printStackTrace();
}
}
//数��文件部署
List<DataSourceInfo> dataSourceInfoList = dataSourceInfoMapper.getAllWithContentByProjectId(projectId);
if (CollectionUtils.isNotEmpty(dataSourceInfoList)) {
for (DataSourceInfo dataSourceInfo : dataSourceInfoList) {
String content = dataSourceInfo.getContent();
File dataSourceFile = new File(rootDir, dataSourceInfo.getName() + ".xml");
try {
FileUtils.writeStringToFile(dataSourceFile, content, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
//测试套件文件部署
List<SuiteRunnerInfo> suiteRunnerInfoList = suiteRunnerInfoMapper.getAllWithContentByProjectId(projectId);
if (CollectionUtils.isNotEmpty(suiteRunnerInfoList)) {
for (SuiteRunnerInfo suiteRunnerInfo : suiteRunnerInfoList) {
String content = suiteRunnerInfo.getContent();
File suiteFile = new File(rootDir, suiteRunnerInfo.getName() + ".xml");
try {
FileUtils.writeStringToFile(suiteFile, content, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "redirect:/project/list.su";
}Example 98
| Project: spring-framework-2.5.x-master File: SimpleJdbcClinic.java View source code |
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.insertOwner = new SimpleJdbcInsert(dataSource).withTableName("owners").usingGeneratedKeyColumns("id");
this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");
this.insertVisit = new SimpleJdbcInsert(dataSource).withTableName("visits").usingGeneratedKeyColumns("id");
}Example 99
| Project: springdoclet-master File: SimpleJdbcClinic.java View source code |
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.insertOwner = new SimpleJdbcInsert(dataSource).withTableName("owners").usingGeneratedKeyColumns("id");
this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");
this.insertVisit = new SimpleJdbcInsert(dataSource).withTableName("visits").usingGeneratedKeyColumns("id");
}Example 100
| Project: Tanaguru-master File: AuditStatisticsFactory.java View source code |
@Autowired
public final void setThemeDataService(ThemeDataService themeDataService) {
Collection<Theme> themeList = themeDataService.findAll();
if (fullThemeMapByRef == null) {
fullThemeMapByRef = new HashMap();
}
// to be associated with a criterion
for (Theme theme : themeList) {
if (!theme.getCriterionList().isEmpty()) {
String referenceCode = theme.getCriterionList().iterator().next().getReference().getCode();
if (!fullThemeMapByRef.containsKey(referenceCode)) {
Collection<Theme> themeListByRef = new ArrayList();
themeListByRef.add(theme);
fullThemeMapByRef.put(referenceCode, themeListByRef);
} else {
fullThemeMapByRef.get(referenceCode).add(theme);
}
}
}
for (Collection<Theme> entry : fullThemeMapByRef.values()) {
sortThemeList(entry);
}
}Example 101
| Project: deadmethods-master File: FindDeadMethods.java View source code |
private void removeSpringMethodsFromAnnotations(ClassRepository repo, Set<String> methods) {
for (ClassInfo classInfo : repo.getAllClassInfos()) {
for (MethodInfo methodInfo : classInfo.getMethodInfo()) {
if ("<init>".equals(methodInfo.getMethodName()) && methodInfo.hasAnnotation("org.springframework.beans.factory.annotation.Autowired")) {
methods.remove(classInfo.getClassName() + ":" + methodInfo);
}
}
}
}