๐Ÿ“ฆ savankansagra / transportOne

๐Ÿ“„ OtpService.java ยท 72 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72package com.transport.services;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.transport.payloads.UserRequestRegister;

@Service
public class OtpService {

	private static final Integer EXPIRE_MINS = 1;
	private LoadingCache<String, Integer> otpCache;

	@Autowired
	private EmailService emailService; 
	
	@Autowired
	private SmsSenderService smsSenderService;
	
	public OtpService() {
		super();
		otpCache = CacheBuilder.newBuilder()
				.expireAfterWrite(EXPIRE_MINS, TimeUnit.MINUTES)
				.build(new CacheLoader<String, Integer>() {
					@Override
					public Integer load(String key) throws Exception {
						return 0;
					}
				});
		
	}
	
	private int generateOtp(String key) {
		Random random = new Random();
		int otp = 100000 + random.nextInt(900000);
		otpCache.put(key, otp);
		return otp;
	}
	
	
	public void generateAndSendtoEmailAndSendtoMobile(UserRequestRegister userRequestRegister) {
		//generate otp
		int otp = this.generateOtp(userRequestRegister.getTelephoneNumber());
		
		//send to email
		String to = userRequestRegister.getUserEmail();
		String subject = "Verification OTP code";
		String message = "Verification OTP code is "+otp;
		try {
			emailService.sendOtpMessage(to, subject, message);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		//send to mobile
		try {
			smsSenderService.sendSmsByService(userRequestRegister.getTelephoneNumber(), otp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}