I am try to implement generic Dao using hibernate and wildfly-10.1.0.Final
BaseDao.java
BaseDao<T, PK extends Serializable> implements BaseDaoI<T, PK>
#Override
public T save(T t) {
try {
this.entityManager.persist(t);
return t;
} catch (PersistenceException pe) {
return null;
}
}
StudentDao.java
public class StudentDao extends BaseDao<Student, Long>{
public StudentDao(EntityManager entityManager) {
super(Student.class, entityManager);
}}
StudentBean.java
#Stateless
public class StudentBean implements StudentBeanLocal {
#PersistenceContext(name = "com.erick_SchoolManagementSystem_war_1.0-SNAPSHOTPU")
EntityManager em;
StudentDao stud = new StudentDao(em);
#Override
public Student add(Student student) {
return stud.save(student);
}
RegisterStudent.java
#EJB
StudentBeanLocal studentbean;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Student student = new Student();
student.setFirst_name(request.getParameter("first_name"));
student.setLast_name(request.getParameter("last_name"));
student.setUsername(request.getParameter("user_name"));
student.setPassword(request.getParameter("password"));
if(studentbean.add(student)!=null){
response.sendRedirect("Login.jsp");
}else{
response.sendRedirect("Register.jsp");
}
When I fill in the form to register and submit, I get the following error:
Caused by: java.lang.NullPointerException
at com.erick.schoolmanagementsystem.dao.BaseDao.save(BaseDao.java:34)
Related
I've been stuck for hours trying to figure out what in the world is going wrong with this Spring Security OAuth2 implementation.
The error occurs when I go to hit the /oauth/token endpoint:
localhost:8080/my-oauth-practice-app/oauth/token
Error: InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter.
AUTHORIZATION SERVER CONFIGURATION
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
AuthenticationManager authenticationManager;
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
endpoints.tokenServices(this.tokenServices).authenticationManager(this.authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
security.tokenKeyAccess("permitAll()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientid").secret("clientpass").authorizedGrantTypes("password").scopes("read").autoApprove(true);
}
}
RESOURCE SERVER CONFIGURATION
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
super.configure(resources);
resources.tokenServices(this.tokenServices);
}
#Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().anyRequest().hasRole("USER");
}
}
GENERAL WEB SECURITY CONFIGURATION
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Primary
#Bean
DefaultTokenServices tokenServices() {
DefaultTokenServices d = new DefaultTokenServices();
d.setAccessTokenValiditySeconds(600);
d.setRefreshTokenValiditySeconds(1000);
d.setTokenStore(new InMemoryTokenStore());
return d;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
You should check WebSecurityConfigurerAdapter method like this:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**", "/oauth/**");
}
remove "/oauth/**" path. otherwise
TokenEndpoint.postAccessToken(Principal principal, #RequestParam Map<String, String> parameters)
principal will be null.
I have following classes
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.pdma.dmapp")
public class AppConfig extends WebMvcConfigurerAdapter{
#Bean(name="multipartResolver")
public StandardServletMultipartResolver resolver(){
return new StandardServletMultipartResolver();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/webResources/**").addResourceLocations("/webResources/");
registry.addResourceHandler("/angularApps/**").addResourceLocations("/angularApps/");
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("GISManager")
.password("gis#manager#pdma")
.roles("GISManager");
}
#Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/**").access("hasRole('GISManager')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
private static final String LOCATION = "D:/uploads/";
private static final long MAX_FILE_SIZE = 1024*1024*25;
private static final long MAX_REQUEST_SIZE = 1024*1024*30;
private static final int FILE_SIZE_THRESHOLD = 0;
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class [] {AppConfig.class,SecurityConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration){
registration.setMultipartConfig(getMultipartConfigElement());
}
private MultipartConfigElement getMultipartConfigElement(){
MultipartConfigElement element = new MultipartConfigElement(LOCATION,
MAX_FILE_SIZE,
MAX_REQUEST_SIZE,
FILE_SIZE_THRESHOLD);
return element;
}
}
WelcomeController.java
#Controller
#RequestMapping(value="/")
public class WelcomeController {
#GetMapping(value="")
public String getWelcomePage(){
return "welcome";
}
}
welcome.jsp is placed in /WEB-INF/views/
I am getting login page and all other pages like main.html etc but I am unable to get welcome page. When I try to hit localhost:8080/dmapp/ I get following message in console:
WARNING: No mapping found for HTTP request with URI [/dmapp/] in DispatcherServlet with name 'dispatcher'
This problem was present before I used spring-security
What can be the problem
changing
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
to
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/"};
}
solved problem in my case
I created an EJB project and another project to test the first.
This screenshot gives an overview about my two projects.
The class main on the test project is:
public class TestEjb
{
public static void main(String[] args)
{
GestionEmployeeRemote gestion = null;
try {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
Object o = context.lookup("ejb:/FirstEJBProject/GestionEmployee!services.GestionEmployeeRemote");
gestion = (GestionEmployeeRemote) o;
} catch (NamingException e) {
e.printStackTrace();
}
createEmployee(gestion);
}
public static void createEmployee(GestionEmployeeRemote gestion)
{
Employee employee = new Employee("Foulen", "Ben Foulen", new Date(), "Directeur");
gestion.createEmployee(employee);
}
The file jndi.properties is:
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=remote://localhost:4447
jboss.naming.client.ejb.context=true
jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
The class GestionEmployee.java is:
package services;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistance.Employee;
/**
* Session Bean implementation class GestionEmployee
*/
#Stateless
public class GestionEmployee implements GestionEmployeeRemote, GestionEmployeeLocal {
#PersistenceContext
EntityManager em;
public GestionEmployee() {
// TODO Auto-generated constructor stub
}
#Override
public void createEmployee(Employee employee) {
em.persist(employee);
}
#Override
public void updateEmployee(Employee employee) {
em.merge(employee);
}
#Override
public void deleteEmployee(Employee employee) {
em.remove(employee);
}
#Override
public Employee getEmployeeById(int idEmployee) {
Employee elmployee = em.find(Employee.class, idEmployee);
return null;
}
#Override
public List<Employee> getAllEmployee() {
Query query = em.createQuery("select e from Employee e");
return query.getResultList();
}
}
The class GestionEmployeeRemote.java is:
package services;
import java.util.List;
import javax.ejb.Remote;
import persistance.Employee;
#Remote
public interface GestionEmployeeRemote
{
public void createEmployee (Employee employee);
public void updateEmployee (Employee employee);
public void deleteEmployee (Employee employee);
public Employee getEmployeeById (int idEmployee);
public List<Employee> getAllEmployee();
}
After running the class main, I got this error:
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:, moduleName:FirstEJBProject, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#a47962
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.createEmployee(Unknown Source)
at test.TestEjb.createEmployee(TestEjb.java:37)
at test.TestEjb.main(TestEjb.java:31)
I'm looking for finding a solution for this issue, any help is appreciated.Thanks a lot.
I'm trying to upgrade Spring Security OAuth2 from 2.0.3 to 2.0.9.
Below is my configuration.
#Configuration
public class SecurityConfig {
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Primary
#Bean
public AuthorizationServerTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
return serviceConfig.clientDetailsService();
}
#Bean
public UserDetailsService clientDetailsUserDetailsService() throws Exception {
return new ClientDetailsUserDetailsService(clientDetailsService());
}
#Bean
public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.afterPropertiesSet();
return filter;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
auth.userDetailsService(clientDetailsUserDetailsService());
}
#Bean(name="authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("zzz/client");
return entryPoint;
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.anonymous().disable()
.requiresChannel().anyRequest().requiresSecure();
http
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler())
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
#Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Autowired
private ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api/**", "/whatever")
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))")
.and()
.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthorizationServerTokenServices tokenServices;
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.withClientDetails(clientDetailsService);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint)
.realm("zzz/clients");
}
}
}
This was working fine with 2.0.3 but now after upgrading to 2.0.9, I started getting "Unsupported grant type: password"
Here is the test;
curl -k -i -H "Accept: application/json" -X POST -d "grant_type=password&client_id=xyz&client_secret=zzzzzz&scope=blah&username=tester&password=121212" https://localhost:8443/myapp/oauth/token
and the result is;
{"error":"unsupported_grant_type","error_description":"Unsupported grant type: password"}
I'm on springframework.version 4.1.8.RELEASE and spring-security.version 3.2.8.RELEASE Really appreciate if I can get help on this.
The problem is that you are configuring to much.
Most of things, such as SessionCreationPolicy, OAuth2AccessDeniedHandler, AuthenticationEntryPoint, ClientCredentialsTokenEndpointFilter are already configured.
Do not confuse between ClientDetailsService and UserDetailsService. Try avoid to use ClientDetailsUserDetailsService if you don't know what it is.
Move #Bean declaration to right position, so they can wired up.
Care with #Order
Try this:
#Configuration
public class SecurityConfig {
#Configuration
#Order(4)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery(
"select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery(
"select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
}
#Bean(name = "authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
// #formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
// TODO put CSRF protection back into this endpoint
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
;
// #formatter:on
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.requestMatchers()
.antMatchers("/api/**", "/whatever")
.and()
.authorizeRequests()
.anyRequest()
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))");
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Primary
#Bean
public DefaultTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
;
return serviceConfig.clientDetailsService();
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices())
.userApprovalHandler(userApprovalHandler());
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.realm("zzz/clients")
.allowFormAuthenticationForClients();
}
}
}
I have a couple of classes as follows:
public class ControllerA {
#Autowired
private UserService userService;
protected void methodControllerA() {
userService.findAll();
....
}
}
public class ControllerB extends ControllerA {
#Autowired
private AccountService accountService;
public void methodControllerB() {
accountService.findAll();
methodControllerA();
}
}
and I want to test the behaviour of ControllerB.methodControllerB(), so I 've created Junit class as follows:
#RunWith(MockitoJUnitRunner.class)
#ContextConfiguration(locations = {
"classpath:services/testServiceContext.xml",
"classpath:apply/applyController.xml",
"classpath:testApplicationContext.xml",
"classpath:testDatabaseMessageSource.xml",
"classpath:controller/propertyeditors/propertyeditorsContext.xml"})
public class ControllerBTest {
#Mock
private AccountService accountService;
#InjectMocks
private ControllerB controller;
#Test
public void methodControllerBTest() throws Exception {
controller = new ControllerB() {
protected void methodControllerA() {
}
};
controller.methodControllerB();
asserts();
}
}
Of course when I instantiate the ControllerB() , accountService is not mocked, so I get a nullpointer when accountService is called, but if I don't instantiate ControllerB() I can't overwrite methodControllerA(), so I get a nullpointer in the Userservice inside this method...
Any ideas ? Thanks
Solved !
AccountServiceImp accountService = mock(AccountServiceImp.class);
controller = new ControllerB() {
protected void methodControllerA() {
}
};
controller.setAccountService(accountService);
controller.methodControllerB();