Error creating bean with name 'registrationListener': Unsatisfied dependency expressed through field 'service' (Showing this after building war)

Viewed 133

These codes runs fine on my STS but not running after making jar/war. also tried with deploying on external tomcat. what is making the differace after making the war?? i am getting lost.

This is the registration listener class

@Component
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {
@Autowired
private IUserService service;

@Autowired
private MessageSource messages;

@Autowired
private JavaMailSender mailSender;

@Autowired
private Environment env;

// API

@Override
public void onApplicationEvent(final OnRegistrationCompleteEvent event) {
    this.confirmRegistration(event);
}

private void confirmRegistration(final OnRegistrationCompleteEvent event) {
    final User user = event.getUser();
    final String token = UUID.randomUUID().toString();
    service.createVerificationTokenForUser(user, token);

    final SimpleMailMessage email = constructEmailMessage(event, user, token);
    mailSender.send(email);
}

//

private SimpleMailMessage constructEmailMessage(final OnRegistrationCompleteEvent event, final User user, final String token) {
    final String recipientAddress = user.getEmail();
    final String subject = "Registration Confirmation";
    final String confirmationUrl = event.getAppUrl() + "/registrationConfirm?token=" + token;
    String message= "Your SECRET for Google Authenticator: "+user.getSecret()+"\n";
    message+= messages.getMessage("message.regSuccLink", null, "You registered successfully. To confirm your registration, please click on the below link.", event.getLocale());
    final SimpleMailMessage email = new SimpleMailMessage();       
    email.setTo(recipientAddress);
    email.setSubject(subject);
    email.setText(message + " \r\n" + confirmationUrl);
    email.setFrom(env.getProperty("support.email"));
    return email;
}

}

I have tried with @Service and without @Service tag

@Service
public interface IUserService {

User registerNewUserAccount(UserDto accountDto);

User getUser(String verificationToken);

void saveRegisteredUser(User user);

void deleteUser(User user);

void createVerificationTokenForUser(User user, String token);

VerificationToken getVerificationToken(String VerificationToken);

VerificationToken generateNewVerificationToken(String token);

void createPasswordResetTokenForUser(User user, String token);

User findUserByEmail(String email);

PasswordResetToken getPasswordResetToken(String token);

Optional<User> getUserByPasswordResetToken(String token);

Optional<User> getUserByID(long id);

void changeUserPassword(User user, String password);

boolean checkIfValidOldPassword(User user, String password);

String validateVerificationToken(String token);

String generateQRUrl(User user) throws UnsupportedEncodingException;

User updateUser2FA(boolean use2FA);

List<String> getUsersFromSessionRegistry();

NewLocationToken isNewLoginLocation(String username, String ip);

String isValidNewLocationToken(String token);

void addUserLocation(User user, String ip);

}

is this where the problem is happening?

@Service
@Transactional
public class UserService implements IUserService {

@Autowired
private UserRepository userRepository;

@Autowired
private VerificationTokenRepository tokenRepository;

@Autowired
private PasswordResetTokenRepository passwordTokenRepository;

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private RoleRepository roleRepository;

@Autowired
private SessionRegistry sessionRegistry;

@Autowired
@Qualifier("GeoIPCountry")
private DatabaseReader databaseReader;

@Autowired
private UserLocationRepository userLocationRepository;

@Autowired
private NewLocationTokenRepository newLocationTokenRepository;

@Autowired
private Environment env;

public static final String TOKEN_INVALID = "invalidToken";
public static final String TOKEN_EXPIRED = "expired";
public static final String TOKEN_VALID = "valid";

public static String QR_PREFIX = "https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=";
public static String APP_NAME = "SpringRegistration";

// API

@Override
public User registerNewUserAccount(final UserDto accountDto) {
    if (emailExists(accountDto.getEmail())) {
        throw new UserAlreadyExistException("There is an account with that email address: " + accountDto.getEmail());
    }
    final User user = new User();

    user.setFirstName(accountDto.getFirstName());
    user.setLastName(accountDto.getLastName());
    user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
    user.setEmail(accountDto.getEmail());
    user.setUsing2FA(accountDto.isUsing2FA());
    user.setRoles(Arrays.asList(roleRepository.findByName("ROLE_USER")));
    return userRepository.save(user);
}

@Override
public User getUser(final String verificationToken) {
    final VerificationToken token = tokenRepository.findByToken(verificationToken);
    if (token != null) {
        return token.getUser();
    }
    return null;
}

@Override
public VerificationToken getVerificationToken(final String VerificationToken) {
    return tokenRepository.findByToken(VerificationToken);
}

@Override
public void saveRegisteredUser(final User user) {
    userRepository.save(user);
}

@Override
public void deleteUser(final User user) {
    final VerificationToken verificationToken = tokenRepository.findByUser(user);

    if (verificationToken != null) {
        tokenRepository.delete(verificationToken);
    }

    final PasswordResetToken passwordToken = passwordTokenRepository.findByUser(user);

    if (passwordToken != null) {
        passwordTokenRepository.delete(passwordToken);
    }

    userRepository.delete(user);
}

@Override
public void createVerificationTokenForUser(final User user, final String token) {
    final VerificationToken myToken = new VerificationToken(token, user);
    tokenRepository.save(myToken);
}

@Override
public VerificationToken generateNewVerificationToken(final String existingVerificationToken) {
    VerificationToken vToken = tokenRepository.findByToken(existingVerificationToken);
    vToken.updateToken(UUID.randomUUID()
        .toString());
    vToken = tokenRepository.save(vToken);
    return vToken;
}

@Override
public void createPasswordResetTokenForUser(final User user, final String token) {
    final PasswordResetToken myToken = new PasswordResetToken(token, user);
    passwordTokenRepository.save(myToken);
}

@Override
public User findUserByEmail(final String email) {
    return userRepository.findByEmail(email);
}

@Override
public PasswordResetToken getPasswordResetToken(final String token) {
    return passwordTokenRepository.findByToken(token);
}

@Override
public Optional<User> getUserByPasswordResetToken(final String token) {
    return Optional.ofNullable(passwordTokenRepository.findByToken(token) .getUser());
}

@Override
public Optional<User> getUserByID(final long id) {
    return userRepository.findById(id);
}

@Override
public void changeUserPassword(final User user, final String password) {
    user.setPassword(passwordEncoder.encode(password));
    userRepository.save(user);
}

@Override
public boolean checkIfValidOldPassword(final User user, final String oldPassword) {
    return passwordEncoder.matches(oldPassword, user.getPassword());
}

@Override
public String validateVerificationToken(String token) {
    final VerificationToken verificationToken = tokenRepository.findByToken(token);
    if (verificationToken == null) {
        return TOKEN_INVALID;
    }

    final User user = verificationToken.getUser();
    final Calendar cal = Calendar.getInstance();
    if ((verificationToken.getExpiryDate()
        .getTime() - cal.getTime()
        .getTime()) <= 0) {
        tokenRepository.delete(verificationToken);
        return TOKEN_EXPIRED;
    }

    user.setEnabled(true);
    // tokenRepository.delete(verificationToken);
    userRepository.save(user);
    return TOKEN_VALID;
}

@Override
public String generateQRUrl(User user) throws UnsupportedEncodingException {
    return QR_PREFIX + URLEncoder.encode(String.format("otpauth://totp/%s:%s?secret=%s&issuer=%s", APP_NAME, user.getEmail(), user.getSecret(), APP_NAME), "UTF-8");
}

@Override
public User updateUser2FA(boolean use2FA) {
    final Authentication curAuth = SecurityContextHolder.getContext()
        .getAuthentication();
    User currentUser = (User) curAuth.getPrincipal();
    currentUser.setUsing2FA(use2FA);
    currentUser = userRepository.save(currentUser);
    final Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser.getPassword(), curAuth.getAuthorities());
    SecurityContextHolder.getContext()
        .setAuthentication(auth);
    return currentUser;
}

private boolean emailExists(final String email) {
    return userRepository.findByEmail(email) != null;
}

@Override
public List<String> getUsersFromSessionRegistry() {
    return sessionRegistry.getAllPrincipals()
        .stream()
        .filter((u) -> !sessionRegistry.getAllSessions(u, false)
            .isEmpty())
        .map(o -> {
            if (o instanceof User) {
                return ((User) o).getEmail();
            } else {
                return o.toString()
        ;
            }
        }).collect(Collectors.toList());
}

@Override
public NewLocationToken isNewLoginLocation(String username, String ip) {

    if(!isGeoIpLibEnabled()) {
        return null;
    }

    try {
        final InetAddress ipAddress = InetAddress.getByName(ip);
        final String country = databaseReader.country(ipAddress)
            .getCountry()
            .getName();
        System.out.println(country + "====****");
        final User user = userRepository.findByEmail(username);
        final UserLocation loc = userLocationRepository.findByCountryAndUser(country, user);
        if ((loc == null) || !loc.isEnabled()) {
            return createNewLocationToken(country, user);
        }
    } catch (final Exception e) {
        return null;
    }
    return null;
}

@Override
public String isValidNewLocationToken(String token) {
    final NewLocationToken locToken = newLocationTokenRepository.findByToken(token);
    if (locToken == null) {
        return null;
    }
    UserLocation userLoc = locToken.getUserLocation();
    userLoc.setEnabled(true);
    userLoc = userLocationRepository.save(userLoc);
    newLocationTokenRepository.delete(locToken);
    return userLoc.getCountry();
}

@Override
public void addUserLocation(User user, String ip) {

    if(!isGeoIpLibEnabled()) {
        return;
    }

    try {
        final InetAddress ipAddress = InetAddress.getByName(ip);
        final String country = databaseReader.country(ipAddress)
            .getCountry()
            .getName();
        UserLocation loc = new UserLocation(country, user);
        loc.setEnabled(true);
        userLocationRepository.save(loc);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

private boolean isGeoIpLibEnabled() {
    return Boolean.parseBoolean(env.getProperty("geo.ip.lib.enabled"));
}

private NewLocationToken createNewLocationToken(String country, User user) {
    UserLocation loc = new UserLocation(country, user);
    loc = userLocationRepository.save(loc);

    final NewLocationToken token = new NewLocationToken(UUID.randomUUID()
        .toString(), loc);
    return newLocationTokenRepository.save(token);
}

} This is my error from jar,war,extarnal tomcat

o.s.b.f.UnsatisfiedDependencyException: Error creating bean with name 'registrationListener': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'databaseReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'GeoIPCountry' defined in class path resource [com/birol/spring/SecSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.maxmind.geoip2.DatabaseReader]: Factory method 'databaseReader' threw exception; nested exception is java.io.FileNotFoundException: src\main\resources\maxmind\GeoLite2-Country.mmdb (The system cannot find the path specified)
at o.s.b.f.a.GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor$AutowiredFieldElement.resolveFieldValue(GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor.java:659)
at o.s.b.f.a.GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor$AutowiredFieldElement.inject(GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor.java:639)
at o.s.b.f.a.InjectionMetadata.inject(InjectionMetadata.java:119)
at o.s.b.f.a.GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor.postProcessProperties(GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DDor.java:399)
at o.s.b.f.s.GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DD.populateBean(GbHi8bXhDyMP2m1NDUSiYmznAJdJzX36DD.java:1431)
... 46 frames truncated
0 Answers
Related