How to create a google Oauth in spring? - spring

I'm new to spring so bear with me :o
I'm using Spring Boot v1.1.8.RELEASE
I'm trying to get a working google Oauth connection with my website.
So I'm trying to get the spring-social-google working while the twitter & facebook one are working.
I read this http://gabiaxel.github.io/spring-social-google-reference/overview.html
I read the tutorial from Spring.io for the other providers(twitter & Facebook).
So here is the code I have :
package app.controllers;
import javax.inject.Inject;
import org.springframework.social.google.api.Google;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/google")
public class GoogleController {
private Google google;
#Inject
public GoogleController(Google google) {
this.google = google;
}
/**
*
* #param model
* #return
*/
#RequestMapping(method = RequestMethod.GET)
public String helloGoogle(Model model) {
if (!google.isAuthorized()) {
return "redirect:/connect/google";
}
model.addAttribute(google.plusOperations().getGoogleProfile());
return "testGoogle";
}
}
I have the files like for facebook in my templates a
googleConnect.html and a googleConnected.html.
Maven is importing correctly the dependencies
The application.properties have the secret and appid from a google
App I created
Here is the error I have :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'googleController' defined in file [C:\Users\Antoine\Documents\NetBeansProjects\p0907931-cinemagik\app\target\classes\app\controllers\GoogleController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.social.google.api.Google]: : No qualifying bean of type [org.springframework.social.google.api.Google] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.social.google.api.Google] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
The bean should be autowired like the other providers right ?
Thanks for your time.
edit :
This bean is working but I don't know how to implement it in my controller ?
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new GoogleConnectionFactory(
environment.getProperty("superAPI"),
environment.getProperty("superSecret")));
return registry;
}
}

Spring Boot only has autoconfig support for Spring Social with Twitter, Facebook and LinkedIn (not Google). You can probably copy the code from the existing implementations and adapt it: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social.

package app.controllers;
import javax.inject.Inject;
import org.springframework.social.google.api.Google;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class GoogleController {
private Google google;
#Inject
public GoogleController(Google google) {
this.google = google;
}
/**
*
* #param model
* #return
*/
#RequestMapping(method = RequestMethod.GET,value="/google")
public String helloGoogle(Model model) {
if (!google.isAuthorized()) {
return "redirect:/connect/google";
}
model.addAttribute(google.plusOperations().getGoogleProfile());
return "testGoogle";
}
}

Related

Why is my configuration test class not working?

I am trying to write unit test using junit for my service configuration class. I have existing code that works in other module, but it doesn't work on this module for some reason and I cannot figure this out. Here is my code:
ServiceConfig class:
package config.service;
import service.Service;
import service.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
#Configuration
public class ServiceConfig {
#Autowired
private Service service;
#Bean
public Service service() {
return new serviceImpl();
}
}
Service interface:
package service;
public interface Service {
void search() throws Exception;
}
ServiceImpl class:
package service;
public class ServiceImpl implements Service {
#Override
public void search() throws Exception {
return null;
}
}
ServiceConfigTest class:
package config.service;
import service.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = { ServiceConfig.class })
public class ServiceConfigTest {
#Autowired
private Service service;
#Test
public void service() {
assertNotNull(service);
}
}
and here is the Exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ServiceConfig': Unsatisfied dependency expressed through field 'Service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.nuance.powershare.dispatchreporter.service.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I don't have too much experience with spring and configuration classes. However, this seems legit to me, I basically followed the code that was already working in other module. My manager also cannot find what is wrong.
The above exception is caused, when we did not create a bean of the type it will raise an exception "Error creating bean with name 'className'.
I tried the same code it's working for me. However, you don't need to create Service Config to create a bean of ServiceImpl just annotate ServiceImpl with #Service and you can test it subsequently.
#Service
public class ServiceImpl implements Service {
#Override
public void search() throws Exception {
}
}
and avoid using the predefined names(ex: Service) for the class name.

No qualifying bean of type repository when running test but not main application

I'm developing a Spring Boot application following TDD methodology. I've created the main classes (controller, service and repository) this way:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class CrimeServiceImpl implements CrimeService{
#Autowired
private CrimeRepository repository;
...
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CrimeController {
#Autowired
private CrimeServiceImpl service = new CrimeServiceImpl();
Repository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CrimeRepository extends JpaRepository<Crime, Long>{
}
This is the project structure:
If I run the application normally, no error. The classes' methods are empty. Then I've created a test class like this:
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = CrimeServiceImpl.class)
#ComponentScan("com.springmiddleware")
#AutoConfigureMockMvc
#SpringBootTest
public class TestCrimeService {
//Calling method getAllCrimes works
#Test
public void returnAllCrimesExists() throws NoSuchMethodException, SecurityException {
List<Crime> list = new ArrayList<>();
assertTrue(this.service.getAllCrimes() == list);
}
And if I run this, the following error is shown and the test fails:
NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmiddleware.repository.CrimeRepository' available: expected at least 1 bean which qualifies as autowire candidate.
I've checked all annotations and it seems to me that all is ok, and I thought if I missed something, even in the normal run the application would fail. What did I got wrong?
I wanted also to make a test class for a JPARepository, and I also encountered the same error message:
NoSuchBeanDefinitionException: No qualifying bean of type
'SomethingRepository' available:
expected at least 1 bean which qualifies as autowire candidate.
I could make it work by adding the 2 following annotations on top of the test class:
#EnableJpaRepositories(basePackageClasses = SomethingRepository.class) // repository
#EntityScan(basePackageClasses = Something.class) // entity of the repository
Now it looks like:
#RunWith(SpringRunner.class)
#EnableJpaRepositories(basePackageClasses = SomethingRepository.class) // repository
#EntityScan(basePackageClasses = Something.class) // entity of the repository
#SpringBootTest(classes = MyDbUnitTestApp.class) // does some #ComponentScan and #EntityScan on the repositories/entities package, and #EnableAutoConfiguration
#ActiveProfiles(Profiles.myTestProfile)
#DatabaseSetup(value = {
"/datasets/dataset1.xml" }, type = DatabaseOperation.CLEAN_INSERT)
public class SomethingRepositoryTest {
#Autowired
private SomethingRepository sut;
#Test
public void findById() {
Something something= sut.findById(1L);
Assert.assertEquals("foobar", something.getName());
}
}

Getting UnsatisfiedDependencyException intermittently for repository

In my project I have created a repository interface by implementing CrudRepository. My underlying DB is Cassandra. I am intermittently getting below error and my application is failing to start -
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userHelper': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.org.retail.userops.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
There are other repository interfaces which are working fine.
My spring boot app -
#SpringBootApplication
#Configuration
#ComponentScan( basePackages = "com.org.retail")
#EnableCassandraRepositories( basePackages = { "com.org.retail.userops.repository" })
public class UserApplication {
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main( String[] args) {
SpringApplication.run(UserApplication.class, args);
}
/**
* Rest template.
*
* #param builder
* the builder
* #return the rest template
*/
#Bean
public RestTemplate restTemplate( RestTemplateBuilder builder) {
return builder.build();
}
}
This is UserRepository interface -
package com.org.retail.userops.repository;
import java.util.List;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.org.retail.userops.domain.User;
public interface UserRepository extends CrudRepository<User, String> {
#Query( "select * from user where userid=?0 and userstatus IN (?1)")
List<User> findByUserIdAndUserStatus( String userId, List<String> statusList);
}
Sometimes application is getting up and sometimes not, so its weird. I am suspecting if there is any Cassandra error while loading repository. Is there any way to see sql errors in startup in spring boot?
Add #Repository (or #Service or #Component) on top of UserRepository class, It might fix the issue.
But if the issue is only intermittent, then there might be some connectivity issues with cassandra DB from you local machine.
To see what queries are going, add these in application.properties file
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.hibernate.type=TRACE
To see what spring is doing behind the scenes or at startup, add this:
logging.level.org.springframework=DEBUG

#Autowired and UnsatisfiedDependencyException in a junit test

i am writing a junit test that have to invoke some method from some autowired dependency which has to interact with Cassandra, but i am getting this exception:
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.21 s <<< FAILURE! - in unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests
[ERROR] testFindByUsername(unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests) Time elapsed: 0.001 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the junit test:
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.util.Version;
import org.springframework.test.context.junit4.SpringRunner;
import example.springdata.cassandra.util.CassandraKeyspace;
import unicon.matthews.admin.AdminUser;
import unicon.matthews.admin.service.repository.AdminUserRepository;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = CassandraConfiguration.class)
public class AdminUserRepositoryTests {
#ClassRule public final static CassandraKeyspace CASSANDRA_KEYSPACE = CassandraKeyspace.onLocalhost().atLeast(Version.parse("3.0"));
#Autowired AdminUserRepository repository;
#Before
public void setUp() throws Exception {
repository.deleteAll();
}
#Test
public void testFindByUsername() {
try {
final String userName = "aironman";
AdminUser.Builder myBuilderAdmin = AdminUser.Builder.class.newInstance();
myBuilderAdmin.withId("id");
myBuilderAdmin.withEmailAddress("some#domain.com");
myBuilderAdmin.withOrgId("orgId");
myBuilderAdmin.withPassword("some-password");
myBuilderAdmin.withSuperAdmin(Boolean.TRUE);
myBuilderAdmin.withTenantId("tenantId");
myBuilderAdmin.withUserName(userName);
//que viene aqui exactamente?
Map<String, String> someMetadata = new HashMap<String, String>();
someMetadata.put("some-key","some-value");
myBuilderAdmin.withMetadata(someMetadata);
AdminUser myAdminUser = myBuilderAdmin.build();
repository.save(myAdminUser);
Optional<AdminUser> loadedUserName = repository.findByUsername(userName);
assertNotNull(loadedUserName);
// assertThat(repository.findOne(homer.id).isPresent(), is(true));
assertEquals("something went wrong!",userName,loadedUserName.get().getUsername());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("Done testFindByUsername!");
}
}
AdminUserRepository looks like:
import java.util.Optional;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import unicon.matthews.admin.AdminUser;
#Repository
public interface AdminUserRepository extends CrudRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}
CassandraConfiguration looks like:
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
#Configuration
#EnableAutoConfiguration
class CassandraConfiguration {
#Configuration
#EnableCassandraRepositories
static class CassandraConfig extends AbstractCassandraConfiguration {
#Override
public String getKeyspaceName() {
return "example";
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.RECREATE;
}
}
}
I understand that spring is trying to instantiate this AdminUserRepository class which is created using CrudRepository from spring-data project. It is supposed that if i mark this interface with #Repository, spring will instantiate the class within the spring context in order that another bean will be capable to autowire it within it, so, why spring is not able to instantiate the dependency?
AdminUserRepository interface is located within src/main/java and AdminUserRepositoryTests is located within src/test/java.
this is my actual pom.xml, please help.
Marking a Spring data repository with #Repository actually doesn't do anything. If you wan't to enable a CrudRepository you need to annotate your configuration with #EnableJpaRepositories. However, since you are using Cassandra I think it's more likely you want to be using a CassandraRepository ?
public interface AdminUserRepository extends CassandraRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}

No qualifying bean of type found for dependency

I´m tri to run a JUnit Test um my spring boot project i bilded like this:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.br.suppcomm.ocp.entity.Login;
public interface LoginDao extends JpaRepository<Login, Long>{
...
}
Service:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.br.suppcomm.ocp.dao.CompanyDAO;
import com.br.suppcomm.ocp.dao.LoginDao;
import com.br.suppcomm.ocp.entity.Login;
#Service
public class LoginService {
#Autowired LoginDao loginDao;
#Autowired CompanyDAO companyDao;
public void save(Login login) {
loginDao.save(login);
}
public void delete(Login login) {
loginDao.delete(login);
}
public Login findById(Login login) {
return loginDao.findOne(login.getLoginId());
}
public Login findByEmail(Login login) {
return loginDao.findByEmail(login.getEmail());
}
public Login FindByLogin(Login login) {
return loginDao.FindByLogin(login);
}
public List<Login> getAll() {
return loginDao.findAll();
}
public Login getUserAccessLoginPass(String login, String password) {
return loginDao.getUserAccessLoginPass(login, password);
}
public void update(Login login) {
loginDao.save(login);
}
}
Test:
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.br.suppcomm.ocp.service.LoginService;
#RunWith(SpringRunner.class)
#SpringBootTest
public class OcpJpaApplicationTests {
#Autowired LoginService loginService;
#Test
public void contextLoads() {
}
}
When I ran this code did show me the folow error.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'loginService': Unsatisfied dependency
expressed through field 'loginDao': No qualifying bean of type
[com.br.suppcomm.ocp.dao.LoginDao] found for dependency
[com.br.suppcomm.ocp.dao.LoginDao]: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.br.suppcomm.ocp.dao.LoginDao] found for
dependency [com.br.suppcomm.ocp.dao.LoginDao]: expected at least 1
bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
I dont know what happened!! Please.
Add #Repository your Interface
annotation , so that it can be Autowired.
#Repository
public interface LoginDao extends JpaRepository<Login, Long>{
}
It'll work that way!
Exception says that SPring is not able to find a qualifier, to Autowired something you need to sterotype it.
Please add the classes attribute to your #SpringBootTest annotation as follows:
#SpringBootTest(classes = { Application.class })
So that it will know that it has to do component scan, etc that you've specified on your Application class.
Add #Repository annotation on LoginDao
You need to add this annotation to your test:
#DataJpaTest
This will cause the Persistence slice of you application to be initialized.

Resources