chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
e396568cc3
commit
5ee51d1913
2918 files changed
+302373
-3
No files matched your search
+14
@@ -0,0 +1,14 @@
|
||||
package com.solvway.services.email;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = {"com.solvway"})
|
||||
public class SolvwayServicesEmailApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SolvwayServicesEmailApplication.class, args);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class Config {
|
||||
@Bean
|
||||
public ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder bCryptPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public interface JpaRepositoryCustom<T> {
|
||||
Page<T> findByPropertyAndPageable(HashMap<String, String> property, PageableRest pageableRest);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MailGunConfig {
|
||||
|
||||
@Value("${mailgun.api.username}")
|
||||
String mailGunAPIUsername;
|
||||
@Value("${mailgun.api.password}")
|
||||
String mailGunAPIPassword;
|
||||
@Value("${mailgun.api.base.url}")
|
||||
String mailGunAPIBaseUrl;
|
||||
@Value("${mailgun.api.messages.url}")
|
||||
String mailGunAPIMessagesUrl;
|
||||
|
||||
@Bean
|
||||
public String mailGunAPIUsername() {
|
||||
return this.mailGunAPIUsername;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public String mailGunAPIPassword() {
|
||||
return this.mailGunAPIPassword;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public String mailGunAPIBaseUrl() {
|
||||
return this.mailGunAPIBaseUrl;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public String mailGunAPIMessagesUrl() {
|
||||
return this.mailGunAPIMessagesUrl;
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
import com.mailjet.client.ClientOptions;
|
||||
import com.mailjet.client.MailjetClient;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class MailjetConfig {
|
||||
|
||||
@Value("${mailjet.api-key}")
|
||||
private String mailjetApiKey;
|
||||
@Value("${mailjet.secret-key}")
|
||||
private String mailjetSecretKey;
|
||||
@Value("${mailjet.sender}")
|
||||
public String mailjetSender;
|
||||
|
||||
@Bean
|
||||
public ClientOptions clientOptions() {
|
||||
return ClientOptions
|
||||
.builder()
|
||||
.apiKey(mailjetApiKey)
|
||||
.apiSecretKey(mailjetSecretKey)
|
||||
.build();
|
||||
}
|
||||
@Bean
|
||||
public MailjetClient mailjetClient() {
|
||||
return new MailjetClient(clientOptions());
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
|
||||
import com.google.cloud.spring.pubsub.PubSubAdmin;
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.google.cloud.spring.pubsub.integration.AckMode;
|
||||
import com.google.cloud.spring.pubsub.integration.inbound.PubSubInboundChannelAdapter;
|
||||
import com.google.pubsub.v1.ExpirationPolicy;
|
||||
import com.google.pubsub.v1.Subscription;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.messaging.MessageChannel;
|
||||
|
||||
@Configuration
|
||||
public class PubSubConfig {
|
||||
|
||||
@Autowired
|
||||
private PubSubAdmin pubSubAdmin;
|
||||
|
||||
@Autowired
|
||||
private SubscriptionAdminClient subscriptionAdminClient;
|
||||
|
||||
@Value("${spring.cloud.gcp.project-id}")
|
||||
public String projectId;
|
||||
|
||||
@Value("${pubsub.email.topic}")
|
||||
public String emailTopic;
|
||||
|
||||
@Value("${pubsub.email.subscription}")
|
||||
public String emailSubscription;
|
||||
|
||||
@Value("${pubsub.sms.topic}")
|
||||
public String smsTopic;
|
||||
|
||||
@Value("${pubsub.sms.subscription}")
|
||||
public String smsSubscription;
|
||||
|
||||
@Value("${pubsub.email.save-request.topic}")
|
||||
public String emailSaveRequestTopic;
|
||||
|
||||
@Value("${pubsub.email.save-request.subscription}")
|
||||
public String emailSaveRequestSubscription;
|
||||
|
||||
@PostConstruct
|
||||
public void newTopic() {
|
||||
if (pubSubAdmin.getTopic(emailTopic) == null) {
|
||||
pubSubAdmin.createTopic(emailTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(smsTopic) == null) {
|
||||
pubSubAdmin.createTopic(smsTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(emailSaveRequestTopic) == null) {
|
||||
pubSubAdmin.createTopic(emailSaveRequestTopic);
|
||||
}
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void newSubscription() {
|
||||
if (pubSubAdmin.getSubscription(emailSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic("projects/" + projectId + "/topics/" + emailTopic)
|
||||
.setName("projects/" + projectId + "/subscriptions/" + emailSubscription)
|
||||
.setRetainAckedMessages(true)
|
||||
.setExpirationPolicy(ExpirationPolicy.newBuilder().build())
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(smsSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic("projects/" + projectId + "/topics/" + smsTopic)
|
||||
.setName("projects/" + projectId + "/subscriptions/" + smsSubscription)
|
||||
.setRetainAckedMessages(true)
|
||||
.setExpirationPolicy(ExpirationPolicy.newBuilder().build())
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(emailSaveRequestSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic("projects/" + projectId + "/topics/" + emailSaveRequestTopic)
|
||||
.setName("projects/" + projectId + "/subscriptions/" + emailSaveRequestSubscription)
|
||||
.setRetainAckedMessages(true)
|
||||
.setExpirationPolicy(ExpirationPolicy.newBuilder().build())
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel emailChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel smsChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel newEmailChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel newRegOrderChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel camundaNewRegistrationChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel newEmailAddUserChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel updateSyncChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel emailSaveRequestChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PubSubInboundChannelAdapter emailChannelAdapter(
|
||||
@Qualifier("emailChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, emailSubscription);
|
||||
adapter.setOutputChannel(inputChannel);
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PubSubInboundChannelAdapter smsChannelAdapter(
|
||||
@Qualifier("smsChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, smsSubscription);
|
||||
adapter.setOutputChannel(inputChannel);
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PubSubInboundChannelAdapter emailSaveRequestChannelAdapter(
|
||||
@Qualifier("emailSaveRequestChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, emailSaveRequestSubscription);
|
||||
adapter.setOutputChannel(inputChannel);
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
|
||||
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.GenericToStringSerializer;
|
||||
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Value("${spring.data.redis.host}")
|
||||
public String hostname;
|
||||
|
||||
@Value("${spring.data.redis.port}")
|
||||
public int port;
|
||||
|
||||
@Bean
|
||||
JedisConnectionFactory jedisConnectionFactory() {
|
||||
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(hostname, port);
|
||||
JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
|
||||
return jedisConFactory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String,Object> redisTemplate() {
|
||||
final RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
|
||||
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(jedisConnectionFactory());
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.solvway.services.email.configuration;
|
||||
|
||||
import com.sendgrid.SendGrid;
|
||||
import lombok.Getter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SendGridConfig {
|
||||
@Value("${send-grid.api-key}")
|
||||
private String sendGridApiKey;
|
||||
@Getter
|
||||
@Value("${send-grid.sender}")
|
||||
private String sendGridSender;
|
||||
|
||||
@Bean
|
||||
public SendGrid sendGrid() {
|
||||
return new SendGrid(sendGridApiKey);
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.solvway.services.email.constants;
|
||||
|
||||
public class EmailConstant {
|
||||
public static final String EMAIL_SENDER = "solvwayEmailTesting@solvway.com";
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.solvway.services.email.constants;
|
||||
|
||||
public interface RestApiDriveServiceConstant {
|
||||
String API_REST_DRIVE_UPLOAD = "/storage/upload";
|
||||
String API_REST_DRIVE_PRIVATE_FILE = "/storage/loadPrivateFile/{filename}";
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.services.email.controller;
|
||||
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.core.enums.EmailEnum.AttachmentStatusType;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.service.AttachmentService;
|
||||
import com.solvway.services.email.service.DriveService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@RequestMapping("/email/attachment")
|
||||
@RestController
|
||||
|
||||
public class AttachmentController {
|
||||
private static final Logger log = LoggerFactory.getLogger(AttachmentController.class);
|
||||
|
||||
@Autowired
|
||||
private AttachmentService attachmentService;
|
||||
@Autowired
|
||||
private DriveService driveService;
|
||||
|
||||
// @PostMapping(value = "/updateAttachment", consumes = { "multipart/form-data" })
|
||||
@RequestMapping(value = { "/updateAttachment" } , method = {RequestMethod.POST} , consumes = { "multipart/form-data" }, produces = { "application/json" })
|
||||
public Attachment storeFile(@RequestParam Map<String,String> requestParams) throws Exception {
|
||||
|
||||
try {
|
||||
// String file_oriname = requestParams.get("file_oriname");
|
||||
String file_name = requestParams.get("file_name");
|
||||
String file_contenttype = requestParams.get("file_contenttype");
|
||||
//byte[] byteArray = requestParams.get("file").getBytes();
|
||||
String base = requestParams.get("base");
|
||||
byte[] byteArray = Base64.getDecoder().decode(base);
|
||||
String bucketFileId="";
|
||||
|
||||
// Check if the file's name contains invalid characters
|
||||
if(file_name.contains("..")) {
|
||||
throw new Exception("Sorry! Filename contains invalid path sequence " + file_name);
|
||||
}
|
||||
try {
|
||||
bucketFileId= driveService.uploadEmailAttachment(file_name, "EmailAttachment_", file_contenttype, byteArray, true);
|
||||
}catch(Exception e) {
|
||||
log.error("Google Cloud Bucket upload failed: {}", e.getMessage());
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
Attachment dbFile = new Attachment(null, file_name, file_contenttype, byteArray, base, LocalDateTime.now(), AttachmentStatusType.Y);
|
||||
dbFile.setBucketFileId(bucketFileId);
|
||||
return attachmentService.save(dbFile);
|
||||
} catch (IOException ex) {
|
||||
log.error(StackTraceUtil.getStackTraceAsJsonString(ex));
|
||||
log.error(ex.getMessage());
|
||||
throw new Exception("Could not store file . Please try again!", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/findById/{id}")
|
||||
public Attachment findById(@PathVariable("id") Long id) {
|
||||
Optional<Attachment> attach = attachmentService.findById(id);
|
||||
|
||||
return attach.orElse(null);
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package com.solvway.services.email.controller;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.PubSubConfig;
|
||||
import com.solvway.core.enums.EmailEnum.AttachmentStatusType;
|
||||
import com.solvway.core.enums.EmailEnum.StatusType;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.service.AttachmentService;
|
||||
import com.solvway.services.email.service.EmailService;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.TypeToken;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Optional;
|
||||
|
||||
@RequestMapping("/email")
|
||||
@RestController
|
||||
|
||||
public class EmailController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EmailController.class);
|
||||
@Autowired
|
||||
private EmailService emailService;
|
||||
|
||||
@Autowired
|
||||
ModelMapper modelMapper;
|
||||
|
||||
@Autowired
|
||||
private PubSubConfig pubSubConfig;
|
||||
|
||||
@Autowired
|
||||
private PubSubTemplate pubSubTemplate;
|
||||
|
||||
@Autowired
|
||||
private PubSubUtil pubSubUtil;
|
||||
|
||||
@Autowired
|
||||
private AttachmentService attachmentService;
|
||||
|
||||
@Value("${email.sender}")
|
||||
private String SENDER;
|
||||
|
||||
@RequestMapping("/findAllPageable")
|
||||
public Page<Email> findAllPageable(@RequestBody PageableRest pageable) {
|
||||
|
||||
Page<Email> emails = emailService.findAllPageable(pageable);
|
||||
|
||||
return emails;
|
||||
}
|
||||
|
||||
@RequestMapping("/findById/{id}")
|
||||
public Email findById(@PathVariable("id") Long id) {
|
||||
Optional<Email> email = emailService.findById(id);
|
||||
|
||||
return email.orElse(null);
|
||||
}
|
||||
|
||||
@RequestMapping("/findByPropertyAndPageable")
|
||||
public Page<Email> findByPropertyAndPageable(@RequestBody HashMap<String, Object> param) {
|
||||
Page<Email> page = Page.empty();
|
||||
try {
|
||||
PageableRest pageable = modelMapper.map(param.get("pageableRest"), PageableRest.class);
|
||||
Type listType = new TypeToken<HashMap<String, String>>() {
|
||||
}.getType();
|
||||
HashMap<String, String> property = modelMapper.map(param.get("property"), listType);
|
||||
page = emailService.findByPropertyAndPageable(property, pageable);
|
||||
} catch (Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
@RequestMapping("/send")
|
||||
public Email send(@RequestBody Email email) {
|
||||
email.setSender(SENDER);
|
||||
try {
|
||||
email.setIsResend(false);
|
||||
email.setResend(0);
|
||||
email = emailService.save(email);
|
||||
if (email.getAttachmentId() != null && !email.getAttachmentId().isEmpty()) {
|
||||
// update attachment emailid
|
||||
for (Long attachId : email.getAttachmentId()) {
|
||||
Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
if (temp != null) {
|
||||
temp.setStatus(AttachmentStatusType.Y);
|
||||
temp.setEmailId(email.getId());
|
||||
attachmentService.save(temp);
|
||||
}
|
||||
}
|
||||
email.setAttachment(attachmentService.findByIdIn(email.getAttachmentId()));
|
||||
} else {
|
||||
email.setAttachment(new ArrayList<>());
|
||||
}
|
||||
|
||||
String topic = pubSubConfig.emailTopic;
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, email);
|
||||
return email;
|
||||
} catch (Exception ignore) {
|
||||
log.error(ignore.getMessage(), ignore);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/resend/{id}")
|
||||
public Email resend(@PathVariable Long id) {
|
||||
|
||||
Email email = emailService.findById(id).get();
|
||||
email.setIsResend(true);
|
||||
|
||||
String topic = pubSubConfig.emailTopic;
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, email);
|
||||
return email;
|
||||
|
||||
// try {
|
||||
// Email email = emailService.findById(id).get();
|
||||
//
|
||||
// //copy and save
|
||||
// Email copyEmail = (Email) email.clone();
|
||||
// copyEmail.setId(null);
|
||||
// copyEmail.setDatetime(LocalDateTime.now());
|
||||
//
|
||||
// for(Attachment temp : copyEmail.getAttachment()) {
|
||||
// if(temp!=null) {
|
||||
// Attachment copy = (Attachment) temp.clone();
|
||||
// copy.setId(null);
|
||||
// Attachment att = attachmentService.save(new Attachment(null,
|
||||
// copy.getFileName(), copy.getFileType(), copy.getData(), copy.getBase(),
|
||||
// LocalDateTime.now(), AttachmentStatusType.Y));
|
||||
// copyEmail.getAttachmentId().add(att.getId());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// copyEmail.setAttachment(null);
|
||||
// List<Recipient> list = new ArrayList<Recipient>();
|
||||
//
|
||||
// for(int i = 0; i < copyEmail.getRecipients().size() ; i ++) {
|
||||
// Recipient copy = (Recipient) copyEmail.getRecipients().get(i).clone();
|
||||
// copy.setId(null);
|
||||
// copy.setEmail(copyEmail);
|
||||
// list.add(copy);
|
||||
// }
|
||||
// copyEmail.setRecipients(null);
|
||||
// copyEmail.setRecipients(list);
|
||||
//
|
||||
// Email copyEmailSend = emailService.save(copyEmail);
|
||||
//
|
||||
// //update attachment emailid
|
||||
// for(Long attachId : copyEmail.getAttachmentId()) {
|
||||
// Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
// if(temp!=null) {
|
||||
// temp.setStatus(AttachmentStatusType.Y);
|
||||
// temp.setEmailId(copyEmailSend.getId());
|
||||
// attachmentService.save(temp);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// copyEmailSend.setAttachment(attachmentService.findByIdIn(copyEmail.getAttachmentId()));
|
||||
//
|
||||
//
|
||||
// String topic = pubSubConfig.emailTopic;
|
||||
// pubSubUtil.publishMessage(pubSubTemplate, topic, copyEmailSend);
|
||||
// return copyEmailSend;
|
||||
// }catch(Exception ignore){
|
||||
// log.error(ignore.getMessage(), ignore);
|
||||
// return null;
|
||||
// }
|
||||
}
|
||||
|
||||
@RequestMapping("/attach/{id}")
|
||||
public Email attch(@PathVariable("id") Long id) {
|
||||
try {
|
||||
Email email = emailService.findById(id).get();
|
||||
String topic = pubSubConfig.emailTopic;
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, email);
|
||||
return email;
|
||||
} catch (Exception ignore) {
|
||||
log.error(ignore.getMessage(), ignore);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/sendEmailWithTamplate")
|
||||
public Email sendEmailWithTamplate(@RequestBody Email email) {
|
||||
email.setSender(SENDER);
|
||||
try {
|
||||
email.setIsResend(false);
|
||||
email.setResend(0);
|
||||
email.setStatus(StatusType.P);
|
||||
email = emailService.save(email);
|
||||
|
||||
if (email.getAttachmentId() != null && !email.getAttachmentId().isEmpty()) {
|
||||
// update attachment emailid
|
||||
for (Long attachId : email.getAttachmentId()) {
|
||||
Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
if (temp != null) {
|
||||
temp.setStatus(AttachmentStatusType.Y);
|
||||
temp.setEmailId(email.getId());
|
||||
attachmentService.save(temp);
|
||||
}
|
||||
}
|
||||
email.setAttachment(attachmentService.findByIdIn(email.getAttachmentId()));
|
||||
} else {
|
||||
email.setAttachment(new ArrayList<>());
|
||||
}
|
||||
|
||||
String topic = pubSubConfig.emailTopic;
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, email);
|
||||
return email;
|
||||
} catch (Exception ignore) {
|
||||
log.error(ignore.getMessage(), ignore);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* @RequestMapping("/gmail/send") public void sendGmail(@RequestBody Email
|
||||
* email) { try { String text = String.format(email.getBody(), "ABC Gmail");
|
||||
* gmailService.sendMessage(email.getRecipient(), email.getSubject(), text,
|
||||
* null); }catch(Exception ignore){ log.error(ignore.getMessage(), ignore); }
|
||||
*
|
||||
* //return true; }
|
||||
*
|
||||
*
|
||||
* @RequestMapping("/mailgun/send") public void sendMailGun(@RequestBody Email
|
||||
* email) { try { String text = String.format(email.getBody(), "ABC MailGun");
|
||||
* mailGunService.sendHTML(email.getSender(), email.getRecipient(),
|
||||
* email.getSubject(), text); }catch(Exception ignore){
|
||||
* log.error(ignore.getMessage(), ignore); }
|
||||
*
|
||||
* //return true; }
|
||||
*/
|
||||
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.solvway.services.email.controller;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.model.PubSubMessageBean;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.PubSubConfig;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import com.solvway.services.email.service.SmsService;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.TypeToken;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashMap;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/email/sms")
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SmsController {
|
||||
private final SmsService smsService;
|
||||
private final ModelMapper modelMapper;
|
||||
private final PubSubConfig pubSubConfig;
|
||||
private final PubSubTemplate pubSubTemplate;
|
||||
private final PubSubUtil pubSubUtil;
|
||||
|
||||
@GetMapping("/findById/{id}")
|
||||
public Optional<Sms> findById(@PathVariable("id") Long id) {
|
||||
return smsService.findById(id);
|
||||
}
|
||||
@GetMapping("/findByUuid/{uuid}")
|
||||
public Optional<Sms> findByUuid(@PathVariable("uuid") String uuid) {
|
||||
return smsService.findByUuid(uuid);
|
||||
}
|
||||
@PostMapping("/findAllPageable")
|
||||
public Page<Sms> findAllPageable(@RequestBody PageableRest pageable) {
|
||||
return smsService.findAllPageable(pageable);
|
||||
}
|
||||
@PostMapping("/findByPropertyAndPageable")
|
||||
public Page<Sms> findByPropertyAndPageable(@RequestBody HashMap<String, Object> param) {
|
||||
Page<Sms> page = Page.empty();
|
||||
try {
|
||||
PageableRest pageable = modelMapper.map(param.get("pageableRest"), PageableRest.class);
|
||||
Type listType = new TypeToken<HashMap<String, String>>() {
|
||||
}.getType();
|
||||
HashMap<String, String> property = modelMapper.map(param.get("property"), listType);
|
||||
page = smsService.findByPropertyAndPageable(property, pageable);
|
||||
} catch (Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
@PostMapping("/send")
|
||||
public Sms send(@RequestBody Sms sms) {
|
||||
sms = smsService.save(sms);
|
||||
String topic = pubSubConfig.smsTopic;
|
||||
PubSubMessageBean pubSubMessageBean = new PubSubMessageBean();
|
||||
pubSubMessageBean.setRef(sms.getUuid());
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, pubSubMessageBean);
|
||||
return sms;
|
||||
}
|
||||
@GetMapping("/resend/{uuid}")
|
||||
public Sms resend(@PathVariable("uuid") String uuid) {
|
||||
Optional<Sms> exist = smsService.findByUuid(uuid);
|
||||
if(exist.isEmpty()){
|
||||
return null;
|
||||
}
|
||||
Sms sms = exist.get();
|
||||
sms.setResend(sms.getResend()+1);
|
||||
sms = smsService.save(sms);
|
||||
String topic = pubSubConfig.smsTopic;
|
||||
PubSubMessageBean pubSubMessageBean = new PubSubMessageBean();
|
||||
pubSubMessageBean.setRef(sms.getUuid());
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, topic, pubSubMessageBean);
|
||||
return sms;
|
||||
}
|
||||
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package com.solvway.services.email.controller;
|
||||
|
||||
import com.github.jknack.handlebars.Handlebars;
|
||||
import com.github.jknack.handlebars.Template;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.core.enums.EmailEnum.AttachmentStatusType;
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.EmailTemplate;
|
||||
import com.solvway.services.email.model.EmailTemplateWithoutAttachment;
|
||||
import com.solvway.services.email.service.AttachmentService;
|
||||
import com.solvway.services.email.service.EmailTemplateWithoutAttachmentService;
|
||||
import com.solvway.services.email.service.TemplateService;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.TypeToken;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@RequestMapping("/email/template")
|
||||
@RestController
|
||||
|
||||
public class TemplateController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EmailController.class);
|
||||
|
||||
@Autowired
|
||||
private TemplateService templateService;
|
||||
|
||||
@Autowired
|
||||
private AttachmentService attachmentService;
|
||||
|
||||
@Autowired
|
||||
private EmailTemplateWithoutAttachmentService emailTemplateWithoutAttachmentService;
|
||||
|
||||
@Autowired
|
||||
ModelMapper modelMapper;
|
||||
|
||||
@RequestMapping("/findAllPageable")
|
||||
public Page<EmailTemplate> findAllPageable(@RequestBody PageableRest pageable) {
|
||||
Page<EmailTemplate> templates = templateService.findAllPageable(pageable);
|
||||
return templates;
|
||||
}
|
||||
|
||||
@RequestMapping("/findById/{id}")
|
||||
public EmailTemplate findById(@PathVariable("id") Long id) {
|
||||
Optional<EmailTemplate> templates = templateService.findById(id);
|
||||
return templates.orElse(null);
|
||||
}
|
||||
|
||||
@RequestMapping("/findByNameAndActive/{name}")
|
||||
public List<EmailTemplate> findByNameAndActive(@PathVariable("name") String name) {
|
||||
List<EmailTemplate> templates = templateService.findByNameAndStatus(name,TemplateStatusType.Y);
|
||||
return templates;
|
||||
}
|
||||
|
||||
@RequestMapping("/findWithoutAttachmentByNameAndActive/{name}")
|
||||
public List<EmailTemplateWithoutAttachment> findWithoutAttachmentByNameAndActive(@PathVariable("name") String name) {
|
||||
List<EmailTemplateWithoutAttachment> templates = emailTemplateWithoutAttachmentService.findByNameAndStatus(name,TemplateStatusType.Y);
|
||||
return templates;
|
||||
}
|
||||
|
||||
@RequestMapping("/findByName/{name}")
|
||||
public EmailTemplate findByName(@PathVariable("name") String name) {
|
||||
Optional<EmailTemplate> templates = templateService.findByName(name);
|
||||
return templates.orElse(null);
|
||||
}
|
||||
|
||||
@RequestMapping("/findByPropertyAndPageable")
|
||||
public Page<EmailTemplate> findByPropertyAndPageable(@RequestBody HashMap<String, Object> param){
|
||||
Page<EmailTemplate> page = Page.empty();
|
||||
try {
|
||||
PageableRest pageable = modelMapper.map(param.get("pageableRest"), PageableRest.class);
|
||||
Type listType = new TypeToken<HashMap<String, String>>() {}.getType();
|
||||
HashMap<String, String> property = modelMapper.map(param.get("property"), listType);
|
||||
page = templateService.findByPropertyAndPageable(property, pageable);
|
||||
}catch(Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
@RequestMapping("/save")
|
||||
public EmailTemplate save(@RequestBody EmailTemplate templateInput) {
|
||||
templateInput.setCreateDateTime(LocalDateTime.now());
|
||||
try {
|
||||
EmailTemplate templt = templateService.save(templateInput);
|
||||
|
||||
//update attachment template_id
|
||||
for(Long attachId : templateInput.getAttachmentId()) {
|
||||
Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
if(temp!=null) {
|
||||
temp.setStatus(AttachmentStatusType.Y);
|
||||
temp.setTemplateId(templt.getId());
|
||||
attachmentService.save(temp);
|
||||
}
|
||||
}
|
||||
return templt;
|
||||
}catch(Exception ignore){
|
||||
log.error(ignore.getMessage(), ignore);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/edit")
|
||||
public EmailTemplate edit(@RequestBody EmailTemplate templateInput) {
|
||||
|
||||
try {
|
||||
EmailTemplate templt = templateService.save(templateInput);
|
||||
|
||||
List<Attachment> list = attachmentService.findByTemplateId(templateInput.getId());
|
||||
if(!list.isEmpty()) {
|
||||
for (Attachment attachment : list) {
|
||||
if (!templateInput.getAttachmentId().contains(attachment.getId()))
|
||||
attachment.setTemplateId(null);
|
||||
}
|
||||
attachmentService.saveAll(list);
|
||||
}
|
||||
|
||||
//update attachment template_id
|
||||
for(Long attachId : templateInput.getAttachmentId()) {
|
||||
Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
if(temp!=null) {
|
||||
temp.setStatus(AttachmentStatusType.Y);
|
||||
temp.setTemplateId(templt.getId());
|
||||
attachmentService.save(temp);
|
||||
}
|
||||
}
|
||||
return templt;
|
||||
}catch(Exception ignore){
|
||||
log.error(ignore.getMessage(), ignore);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping("/retriveTemplateAndMapping")
|
||||
public EmailTemplate retriveTemplateByIdOrName(@RequestBody EmailTemplate template) {
|
||||
EmailTemplate templates = null;
|
||||
|
||||
if(template.getId() != null) {
|
||||
templates = templateService.findById(template.getId()).orElse(null);
|
||||
}
|
||||
|
||||
if(templates == null && template.getName() != null) {
|
||||
templates = templateService.findByName(template.getName()).orElse(null);
|
||||
}
|
||||
|
||||
if(templates == null)
|
||||
return null;
|
||||
else {
|
||||
Handlebars handlebars = new Handlebars();
|
||||
try {
|
||||
Template templt = handlebars.compileInline(templates.getBody());
|
||||
String templateString = templt.apply(template.getObj());
|
||||
template.setBody(templateString);
|
||||
return template;
|
||||
} catch (IOException e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// @RequestMapping("/edit")
|
||||
// public Template edit(@RequestBody Template template) {
|
||||
//
|
||||
// //reset attachment to N
|
||||
// attachmentService.inactiveByTemplateId(template.getId());
|
||||
// for(Long attachId : template.getAttachmentId()) {
|
||||
// Attachment temp = attachmentService.findById(attachId).orElse(null);
|
||||
// if(temp!=null) {
|
||||
// temp.setStatus(AttachmentStatusType.Y);
|
||||
// temp.setTemplateId(template.getId());
|
||||
// attachmentService.save(temp);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// //udpate template
|
||||
// Template templt = templateService.save(template);
|
||||
// templt.setAttachment(attachmentService.findByIdIn(template.getAttachmentId()));
|
||||
// return templt;
|
||||
// }
|
||||
//
|
||||
//
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import com.solvway.core.enums.EmailEnum.AttachmentStatusType;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
public class Attachment implements Cloneable{
|
||||
@Setter
|
||||
@Getter
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Setter
|
||||
@Getter
|
||||
private String fileName;
|
||||
@Setter
|
||||
@Getter
|
||||
private String fileType;
|
||||
@Setter
|
||||
@Getter
|
||||
@Transient
|
||||
private byte[] data;
|
||||
@Setter
|
||||
@Getter
|
||||
@Transient
|
||||
private String base;
|
||||
@Setter
|
||||
@Getter
|
||||
private LocalDateTime datetime;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private AttachmentStatusType status = AttachmentStatusType.Y;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "template_id", referencedColumnName = "id", insertable = false, updatable = false)
|
||||
private EmailTemplate template;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Column(name = "template_id")
|
||||
private Long templateId;
|
||||
|
||||
@JsonBackReference(value="email-attachment")
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "email_id", referencedColumnName = "id", insertable = false, updatable = false)
|
||||
private Email email;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Column(name = "email_id")
|
||||
private Long emailId;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
private String bucketFileId;
|
||||
|
||||
|
||||
public Attachment() {
|
||||
super();
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public Attachment(Long id, String fileName, String fileType, byte[] data,String base,LocalDateTime datetime, AttachmentStatusType status) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.fileName = fileName;
|
||||
this.fileType = fileType;
|
||||
this.data = data;
|
||||
this.base = base;
|
||||
this.datetime = datetime;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
|
||||
public Object clone() throws CloneNotSupportedException
|
||||
{
|
||||
return super.clone();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||
import com.solvway.services.email.constants.EmailConstant;
|
||||
import com.solvway.core.enums.EmailEnum.StatusType;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
public class Email implements Cloneable{
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String sender = EmailConstant.EMAIL_SENDER;
|
||||
private String subject;
|
||||
private String body;
|
||||
@Column(updatable = false)
|
||||
private LocalDateTime datetime = LocalDateTime.now();
|
||||
|
||||
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private StatusType status;
|
||||
|
||||
private Integer resend;
|
||||
|
||||
@JsonManagedReference(value="email-recipient")
|
||||
@OneToMany(cascade = CascadeType.ALL, mappedBy = "email")
|
||||
private List<Recipient> recipients;
|
||||
|
||||
@JsonManagedReference(value="email-attachment")
|
||||
@OneToMany(cascade = CascadeType.ALL, mappedBy = "email")
|
||||
private List<Attachment> attachment;
|
||||
|
||||
@Transient
|
||||
private List<Long> attachmentId = new ArrayList<>();
|
||||
|
||||
@Transient
|
||||
private Boolean isResend;
|
||||
|
||||
public Object clone() throws CloneNotSupportedException
|
||||
{
|
||||
return super.clone();
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name="template")
|
||||
public class EmailTemplate {
|
||||
|
||||
public enum Lang {
|
||||
CN("CN"),ZH("ZH"),EN("EN"),MY("MY"),ID("ID");
|
||||
private final String lang;
|
||||
Lang(String lang) {
|
||||
this.lang=lang;
|
||||
}
|
||||
public String getFileLang() {
|
||||
return this.lang;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String subject;
|
||||
private String name;
|
||||
private String description;
|
||||
private String body;
|
||||
private String doneBy;
|
||||
private LocalDateTime createDateTime;
|
||||
|
||||
@OneToMany(mappedBy = "template")
|
||||
private List<Attachment> attachment;
|
||||
|
||||
@Transient
|
||||
private List<Long> attachmentId = new ArrayList<>();
|
||||
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private TemplateStatusType status;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Lang lang;
|
||||
|
||||
@Transient
|
||||
private Object obj;
|
||||
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name="template")
|
||||
public class EmailTemplateWithoutAttachment {
|
||||
|
||||
|
||||
public enum Lang {
|
||||
CN("CN"),ZH("ZH"),EN("EN"),MY("MY"),ID("ID");
|
||||
private final String lang;
|
||||
Lang(String lang) {
|
||||
this.lang=lang;
|
||||
}
|
||||
public String getFileLang() {
|
||||
return this.lang;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String subject;
|
||||
private String name;
|
||||
private String description;
|
||||
private String body;
|
||||
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private TemplateStatusType status;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Lang lang;
|
||||
|
||||
@Transient
|
||||
private Object obj;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import com.solvway.core.enums.EmailEnum.RecipientType;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Entity
|
||||
public class Recipient implements Cloneable{
|
||||
|
||||
@Getter
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Getter
|
||||
@NotNull
|
||||
private String recipient;
|
||||
@Getter
|
||||
@NotNull
|
||||
@Enumerated(EnumType.STRING)
|
||||
private RecipientType type;
|
||||
|
||||
@JsonBackReference(value="email-recipient")
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "email_id", referencedColumnName = "id")
|
||||
private Email email;
|
||||
|
||||
|
||||
public Object clone() throws CloneNotSupportedException {
|
||||
return super.clone();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.solvway.services.email.model;
|
||||
|
||||
import com.solvway.core.converter.ListToJsonColumnConverter;
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.core.utils.SnowflakeIdWorker;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
public class Sms {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(updatable = false)
|
||||
private String uuid = SnowflakeIdWorker.getUUIDStr();
|
||||
private LocalDateTime datetime=LocalDateTime.now();
|
||||
private String recipient;
|
||||
private String content;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private SmsEnum.SmsStatus status=SmsEnum.SmsStatus.P;
|
||||
private int resend;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private SmsEnum.SmsProvider provider = SmsEnum.SmsProvider.SMSS360;
|
||||
@Convert(converter = ListToJsonColumnConverter.class)
|
||||
private List<String> providerResponse = new ArrayList<>();
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.solvway.services.email.pubsub;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
|
||||
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.core.model.PubSubMessageBean;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.enums.EmailEnum.StatusType;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import com.solvway.services.email.service.EmailClientService;
|
||||
import com.solvway.services.email.service.EmailService;
|
||||
import com.solvway.services.email.service.SmsClientService;
|
||||
import com.solvway.services.email.service.SmsService;
|
||||
import com.solvway.services.email.util.RedisUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.integration.annotation.ServiceActivator;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Optional;
|
||||
|
||||
@Configuration
|
||||
public class PubSubListener {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PubSubListener.class);
|
||||
|
||||
@Autowired
|
||||
private EmailService emailService;
|
||||
@Autowired
|
||||
private SmsService smsService;
|
||||
@Autowired
|
||||
private RedisUtil<String> redisUtil;
|
||||
@Autowired
|
||||
private PubSubUtil pubSubUtil;
|
||||
@Autowired
|
||||
private EmailClientService emailClientService;
|
||||
@Autowired
|
||||
private SmsClientService smsClientService;
|
||||
@Autowired
|
||||
private PubSubTemplate pubSubTemplate;
|
||||
|
||||
@Value("${pubsub.email.topic}")
|
||||
private String emailTopic;
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "emailChannel")
|
||||
public MessageHandler emailChannelReceiver() {
|
||||
return message -> {
|
||||
|
||||
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
|
||||
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
|
||||
|
||||
try {
|
||||
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
Email email = pubSubUtil.convertToOriginalObjectWithCustomObjectMapper(message.getPayload(), Email.class);
|
||||
boolean success = false;
|
||||
try {
|
||||
emailClientService.sendEmail(email, email.getAttachment());
|
||||
originalMessage.ack();
|
||||
success = true;
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getLocalizedMessage(), ex);
|
||||
originalMessage.ack();
|
||||
}
|
||||
|
||||
emailService.setStatusForEmail(success ? StatusType.Y : StatusType.N, email.getId());
|
||||
|
||||
if (email.getIsResend() != null && email.getIsResend() && success) {
|
||||
Integer resendCount = email.getResend();
|
||||
emailService.setIncreaseResendCountForEmail(resendCount + 1, email.getId());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getLocalizedMessage(), ex);
|
||||
try {
|
||||
pubSubUtil.deleteMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
} catch (Exception e) {
|
||||
log.error(e.getLocalizedMessage(), e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "smsChannel")
|
||||
public MessageHandler smsChannelReceiver() {
|
||||
return message -> {
|
||||
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
|
||||
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
|
||||
try {
|
||||
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
PubSubMessageBean pubSubMessageBean = pubSubUtil.convertToOriginalObjectWithCustomObjectMapper(message.getPayload(), PubSubMessageBean.class);
|
||||
String uuid = pubSubMessageBean.getRef();
|
||||
Optional<Sms> sms = smsService.findByUuid(uuid);
|
||||
if (sms.isEmpty()) {
|
||||
log.info("SMS not found : {}", uuid);
|
||||
} else if (sms.get().getStatus().equals(SmsEnum.SmsStatus.P)) {
|
||||
Sms result = smsClientService.sendSms(sms.get());
|
||||
smsService.setStatusForSms(result.getStatus(), result.getId());
|
||||
smsService.setProviderResponseForSms(result.getProviderResponse(), result.getId());
|
||||
}
|
||||
originalMessage.ack();
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getLocalizedMessage(), ex);
|
||||
try {
|
||||
pubSubUtil.deleteMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
} catch (Exception e) {
|
||||
log.error(e.getLocalizedMessage(), e);
|
||||
}
|
||||
} finally {
|
||||
//Always ack to prevent infinite loop and used up credit
|
||||
originalMessage.ack();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "emailSaveRequestChannel")
|
||||
public MessageHandler emailSaveRequestReceiver() {
|
||||
return message -> {
|
||||
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
|
||||
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
|
||||
try {
|
||||
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
Email email = pubSubUtil.convertToOriginalObjectWithCustomObjectMapper(message.getPayload(), Email.class);
|
||||
email.setIsResend(false);
|
||||
email.setResend(0);
|
||||
email.setStatus(StatusType.P);
|
||||
email.setAttachment(new ArrayList<>());
|
||||
Email saved = emailService.save(email);
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, emailTopic, saved);
|
||||
originalMessage.ack();
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getLocalizedMessage(), ex);
|
||||
try {
|
||||
pubSubUtil.deleteMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
} catch (Exception e) {
|
||||
log.error(e.getLocalizedMessage(), e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
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 java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface AttachmentRepository extends JpaRepository<Attachment, Long>{
|
||||
|
||||
List<Attachment> findByIdIn(List<Long> ids);
|
||||
|
||||
@Query("select k from Attachment k where k.templateId = :templateId")
|
||||
List<Attachment> findByTemplateId(@Param("templateId") Long templateId);
|
||||
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.core.enums.EmailEnum.StatusType;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface EmailRepository extends JpaRepository<Email, Long>, JpaRepositoryCustom<Email> {
|
||||
|
||||
@Modifying
|
||||
@Query("update Email e set e.status = :status where e.id = :id")
|
||||
int setStatusForEmail(@Param("status") StatusType status, @Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Email e set e.resend = :resend where e.id = :id")
|
||||
int setIncreaseResendCountForEmail(@Param("resend") Integer resend, @Param("id") Long id);
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.*;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public class EmailRepositoryImpl implements JpaRepositoryCustom<Email>{
|
||||
private static final Logger log = LoggerFactory.getLogger(EmailRepositoryImpl.class);
|
||||
@Autowired
|
||||
EntityManager em;
|
||||
@Autowired
|
||||
DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
|
||||
/*
|
||||
* Use JPA Criteria to search
|
||||
* */
|
||||
@Override
|
||||
public Page<Email> findByPropertyAndPageable(HashMap<String, String> property, PageableRest pageableRest) {
|
||||
Pageable pageable = PageRequest.of(pageableRest.getNumber(), pageableRest.getSize(), pageableRest.getSort());
|
||||
Sort sort = pageableRest.getSort();
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Email> cq = cb.createQuery(Email.class);
|
||||
Root<Email> root = cq.from(Email.class);
|
||||
|
||||
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
|
||||
Root<Email> rootCount = countQuery.from(Email.class);
|
||||
|
||||
List<Email> resultList = new ArrayList<>();
|
||||
Long count = 0L;
|
||||
try {
|
||||
//[START] Criteria Searching
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
List<Predicate> predicatesCount = new ArrayList<>();
|
||||
ArrayList<String> keyList = new ArrayList<>(property.keySet());
|
||||
|
||||
keyList.forEach(k->{
|
||||
String value = property.get(k);
|
||||
if(StringUtils.hasLength(value)) {
|
||||
switch (k) {
|
||||
case "id" -> {
|
||||
predicates.add(cb.equal(root.get(k), Long.parseLong(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get(k), Long.parseLong(value)));
|
||||
}
|
||||
case "sender" -> {
|
||||
predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
}
|
||||
case "startDate" -> {
|
||||
try {
|
||||
LocalDate date = dateTimeFormatterUtil.parseDate(value);
|
||||
predicates.add(cb.greaterThanOrEqualTo(root.get("datetime"), date.atStartOfDay()));
|
||||
predicatesCount.add(cb.greaterThanOrEqualTo(rootCount.get("datetime"), date.atStartOfDay()));
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
case "endDate" -> {
|
||||
try {
|
||||
LocalDate date = dateTimeFormatterUtil.parseDate(value);
|
||||
predicates.add(cb.lessThanOrEqualTo(root.get("datetime"), date.atTime(23, 59, 59)));
|
||||
predicatesCount.add(cb.lessThanOrEqualTo(rootCount.get("datetime"), date.atTime(23, 59, 59)));
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
case "subject" -> {
|
||||
predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
}
|
||||
// case "recipient" -> {
|
||||
// predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
// predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
// }
|
||||
case "recipient" -> {
|
||||
// Join with the recipients
|
||||
Join<Email, Recipient> recipientJoin = root.join("recipients", JoinType.LEFT);
|
||||
Join<Email, Recipient> recipientJoinCount = rootCount.join("recipients", JoinType.LEFT);
|
||||
|
||||
// Filter on the recipient field in the Recipient entity
|
||||
predicates.add(cb.like(recipientJoin.get("recipient"), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(recipientJoinCount.get("recipient"), "%" + value + "%"));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
//[END] Criteria Searching
|
||||
|
||||
//Generate Query with criteria
|
||||
cq.where(predicates.toArray(new Predicate[0]));
|
||||
|
||||
//[START] Order by
|
||||
List<Order> orderList = new ArrayList<>();
|
||||
sort.forEach(o->{
|
||||
if(o.isAscending()) {
|
||||
orderList.add(cb.asc(root.get(o.getProperty())));
|
||||
}else {
|
||||
orderList.add(cb.desc(root.get(o.getProperty())));
|
||||
}
|
||||
});
|
||||
cq.orderBy(orderList);
|
||||
//[END] Order by
|
||||
|
||||
//Execute Generated Query
|
||||
resultList = em.createQuery(cq).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();
|
||||
|
||||
//Count Query
|
||||
countQuery.select(cb.count(rootCount)).where(predicatesCount.toArray(new Predicate[0]));
|
||||
//Fetch the count of records
|
||||
count = em.createQuery(countQuery).getSingleResult();
|
||||
|
||||
}catch(Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return new PageImpl<>(resultList, pageable, count);
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.EmailTemplateWithoutAttachment;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface EmailTemplateWithoutAttachmentRepository extends JpaRepository<EmailTemplateWithoutAttachment, Long> {
|
||||
List<EmailTemplateWithoutAttachment> findByNameAndStatus(String name, TemplateStatusType status);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface RecipientRepository extends JpaRepository<Recipient, Long>{
|
||||
|
||||
|
||||
// @Modifying
|
||||
// @Query("update Recipient e set e.status = :status where e.templateId = :templateId")
|
||||
// int inactiveByTemplateId(@Param("status") RecipientStatusType status, @Param("templateId") Long templateId);
|
||||
//
|
||||
//List<Recipient> saveAll(List<Recipient> rcps);
|
||||
|
||||
}
|
||||
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface SmsRepository extends JpaRepository<Sms, Long>, JpaRepositoryCustom<Sms> {
|
||||
@Modifying
|
||||
@Query("update Sms e set e.status = :status where e.id = :id")
|
||||
int setStatusForSms(@Param("status") SmsEnum.SmsStatus status, @Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Sms e set e.resend = :resend where e.id = :id")
|
||||
int setIncreaseResendCountForSms(@Param("resend") Integer resend, @Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Sms e set e.providerResponse = :providerResponse where e.id = :id")
|
||||
int setProviderResponseForSms(@Param("providerResponse") List<String> providerResponse, @Param("id") Long id);
|
||||
|
||||
Optional<Sms> findByUuid(String uuid);
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.*;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public class SmsRepositoryImpl implements JpaRepositoryCustom<Sms>{
|
||||
private static final Logger log = LoggerFactory.getLogger(SmsRepositoryImpl.class);
|
||||
@Autowired
|
||||
EntityManager em;
|
||||
@Autowired
|
||||
DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
|
||||
/*
|
||||
* Use JPA Criteria to search
|
||||
* */
|
||||
@Override
|
||||
public Page<Sms> findByPropertyAndPageable(HashMap<String, String> property, PageableRest pageableRest) {
|
||||
Pageable pageable = PageRequest.of(pageableRest.getNumber(), pageableRest.getSize(), pageableRest.getSort());
|
||||
Sort sort = pageableRest.getSort();
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Sms> cq = cb.createQuery(Sms.class);
|
||||
Root<Sms> root = cq.from(Sms.class);
|
||||
|
||||
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
|
||||
Root<Sms> rootCount = countQuery.from(Sms.class);
|
||||
|
||||
List<Sms> resultList = new ArrayList<>();
|
||||
Long count = 0L;
|
||||
try {
|
||||
//[START] Criteria Searching
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
List<Predicate> predicatesCount = new ArrayList<>();
|
||||
ArrayList<String> keyList = new ArrayList<>(property.keySet());
|
||||
|
||||
keyList.forEach(k->{
|
||||
String value = property.get(k);
|
||||
if(StringUtils.hasLength(value)) {
|
||||
switch (k) {
|
||||
case "recipient", "content" -> {
|
||||
predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
}
|
||||
case "startDate" -> {
|
||||
try {
|
||||
LocalDate date = dateTimeFormatterUtil.parseDate(value);
|
||||
predicates.add(cb.greaterThanOrEqualTo(root.get("datetime"), date.atStartOfDay()));
|
||||
predicatesCount.add(cb.greaterThanOrEqualTo(rootCount.get("datetime"), date.atStartOfDay()));
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
case "endDate" -> {
|
||||
try {
|
||||
LocalDate date = dateTimeFormatterUtil.parseDate(value);
|
||||
predicates.add(cb.lessThanOrEqualTo(root.get("datetime"), date.atTime(23, 59, 59)));
|
||||
predicatesCount.add(cb.lessThanOrEqualTo(rootCount.get("datetime"), date.atTime(23, 59, 59)));
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
case "status" -> {
|
||||
predicates.add(cb.equal(root.get("status"), SmsEnum.SmsStatus.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get("status"), SmsEnum.SmsStatus.valueOf(value)));
|
||||
}
|
||||
case "provider"-> {
|
||||
predicates.add(cb.equal(root.get("provider"), SmsEnum.SmsProvider.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get("provider"), SmsEnum.SmsProvider.valueOf(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
//[END] Criteria Searching
|
||||
|
||||
//Generate Query with criteria
|
||||
cq.where(predicates.toArray(new Predicate[0]));
|
||||
|
||||
//[START] Order by
|
||||
List<Order> orderList = new ArrayList<>();
|
||||
sort.forEach(o->{
|
||||
if(o.isAscending()) {
|
||||
orderList.add(cb.asc(root.get(o.getProperty())));
|
||||
}else {
|
||||
orderList.add(cb.desc(root.get(o.getProperty())));
|
||||
}
|
||||
});
|
||||
cq.orderBy(orderList);
|
||||
//[END] Order by
|
||||
|
||||
//Execute Generated Query
|
||||
resultList = em.createQuery(cq).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();
|
||||
|
||||
//Count Query
|
||||
countQuery.select(cb.count(rootCount)).where(predicatesCount.toArray(new Predicate[0]));
|
||||
//Fetch the count of records
|
||||
count = em.createQuery(countQuery).getSingleResult();
|
||||
|
||||
}catch(Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return new PageImpl<>(resultList, pageable, count);
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.EmailTemplate;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface TemplateRepository extends JpaRepository<EmailTemplate, Long>, JpaRepositoryCustom<EmailTemplate>{
|
||||
|
||||
Optional<EmailTemplate> findByName(String name);
|
||||
|
||||
List<EmailTemplate> findByNameAndStatus(String name, TemplateStatusType status);
|
||||
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.solvway.services.email.repo;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.JpaRepositoryCustom;
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.EmailTemplate;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.*;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public class TemplateRepositoryImpl implements JpaRepositoryCustom<EmailTemplate>{
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EmailRepositoryImpl.class);
|
||||
@Autowired
|
||||
EntityManager em;
|
||||
@Autowired
|
||||
DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
|
||||
/*
|
||||
* Use JPA Criteria to search
|
||||
* */
|
||||
@Override
|
||||
public Page<EmailTemplate> findByPropertyAndPageable(HashMap<String, String> property, PageableRest pageableRest) {
|
||||
Pageable pageable = PageRequest.of(pageableRest.getNumber(), pageableRest.getSize(), pageableRest.getSort());
|
||||
Sort sort = pageableRest.getSort();
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<EmailTemplate> cq = cb.createQuery(EmailTemplate.class);
|
||||
Root<EmailTemplate> root = cq.from(EmailTemplate.class);
|
||||
|
||||
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
|
||||
Root<EmailTemplate> rootCount = countQuery.from(EmailTemplate.class);
|
||||
|
||||
List<EmailTemplate> resultList = new ArrayList<>();
|
||||
Long count = 0l;
|
||||
try {
|
||||
//[START] Criteria Searching
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
List<Predicate> predicatesCount = new ArrayList<>();
|
||||
ArrayList<String> keyList = new ArrayList<>(property.keySet());
|
||||
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
|
||||
|
||||
keyList.forEach(k->{
|
||||
String value = property.get(k);
|
||||
if(StringUtils.hasLength(value)) {
|
||||
switch (k) {
|
||||
case "id" -> {
|
||||
predicates.add(cb.equal(root.get(k), Long.parseLong(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get(k), Long.parseLong(value)));
|
||||
}
|
||||
case "status" -> {
|
||||
predicates.add(cb.equal(root.get(k), TemplateStatusType.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get(k), TemplateStatusType.valueOf(value)));
|
||||
}
|
||||
case "name" -> {
|
||||
predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
}
|
||||
case "description" -> {
|
||||
predicates.add(cb.like(root.get(k), "%" + value + "%"));
|
||||
predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%"));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
//[END] Criteria Searching
|
||||
|
||||
//Generate Query with criteria
|
||||
cq.where(predicates.toArray(new Predicate[0]));
|
||||
|
||||
//[START] Order by
|
||||
List<Order> orderList = new ArrayList<>();
|
||||
sort.forEach(o->{
|
||||
if(o.isAscending()) {
|
||||
orderList.add(cb.asc(root.get(o.getProperty())));
|
||||
}else {
|
||||
orderList.add(cb.desc(root.get(o.getProperty())));
|
||||
}
|
||||
});
|
||||
cq.orderBy(orderList);
|
||||
//[END] Order by
|
||||
|
||||
//Execute Generated Query
|
||||
resultList = em.createQuery(cq).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();
|
||||
|
||||
//Count Query
|
||||
countQuery.select(cb.count(rootCount)).where(predicatesCount.toArray(new Predicate[0]));
|
||||
//Fetch the count of records
|
||||
count = em.createQuery(countQuery).getSingleResult();
|
||||
}catch(Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
return new PageImpl<>(resultList, pageable, count);
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.repo.AttachmentRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
|
||||
@Service
|
||||
public class AttachmentService {
|
||||
|
||||
@Autowired
|
||||
private AttachmentRepository attachmentRepository;
|
||||
|
||||
@Transactional
|
||||
public Attachment save(Attachment file) {
|
||||
return attachmentRepository.save(file);
|
||||
}
|
||||
|
||||
public Optional<Attachment> findById(Long id) {
|
||||
return attachmentRepository.findById(id);
|
||||
}
|
||||
|
||||
public List<Attachment> findByIdIn(List<Long> ids){
|
||||
return attachmentRepository.findByIdIn(ids);
|
||||
}
|
||||
|
||||
public List<Attachment> findByTemplateId(Long Id){
|
||||
return attachmentRepository.findByTemplateId(Id);
|
||||
}
|
||||
|
||||
public List<Attachment> saveAll(List<Attachment> attcs){
|
||||
return attachmentRepository.saveAll(attcs);
|
||||
}
|
||||
|
||||
//
|
||||
// @Transactional
|
||||
// public int setEmailId(Long emailId, List<Long> id) {
|
||||
// return attachmentRepository.setEmailId(emailId, id);
|
||||
// }
|
||||
//
|
||||
// @Transactional
|
||||
// public int setTemplateId(Long templateId, List<Long> id) {
|
||||
// return attachmentRepository.setTemplateId(templateId, id);
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.constant.SystemConstants;
|
||||
import com.solvway.core.utils.RestTemplateUtil;
|
||||
import com.solvway.services.email.constants.RestApiDriveServiceConstant;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
|
||||
@Service
|
||||
public class DriveService {
|
||||
@Autowired
|
||||
private RestTemplateUtil restTemplateUtil;
|
||||
|
||||
public String uploadEmailAttachment(String filename, String filenamePrepend, String contentType, byte[] fileBytes, boolean isPrivate) throws IOException {
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
|
||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||
//body.add("file", new FileSystemResource(path.toFile()));
|
||||
|
||||
body.add("file_oriname", filename);
|
||||
body.add("file_name", filename);
|
||||
body.add("file_contenttype", contentType);
|
||||
body.add("file_private", isPrivate? "Y":"N");
|
||||
body.add("file_name_prepend", filenamePrepend);
|
||||
body.add("file_email_attachment", "Y");
|
||||
// Email attachments have no form-submit/commit step, so make them permanent on upload
|
||||
// (not pending-tagged and never subject to the pending-expiry lifecycle rule).
|
||||
body.add("file_autocommit", "Y");
|
||||
body.add("file", Base64.getEncoder().encodeToString(fileBytes));
|
||||
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
|
||||
|
||||
ResponseEntity<String> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(SystemConstants.SERVICE_ID_DRIVE,
|
||||
RestApiDriveServiceConstant.API_REST_DRIVE_UPLOAD),
|
||||
requestEntity,
|
||||
String.class);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
public byte[] loadPrivateFile(String filename) {
|
||||
ResponseEntity<byte[]> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(SystemConstants.SERVICE_ID_DRIVE,
|
||||
RestApiDriveServiceConstant.API_REST_DRIVE_PRIVATE_FILE),
|
||||
byte[].class, filename);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
|
||||
import java.util.List;
|
||||
public interface EmailClientService {
|
||||
boolean sendEmail(Email email, List<Attachment> attch);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.RecipientType;
|
||||
import com.solvway.core.enums.EmailEnum.StatusType;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import com.solvway.services.email.repo.EmailRepository;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class EmailService {
|
||||
|
||||
@Autowired
|
||||
private EmailRepository emailRepository;
|
||||
|
||||
public Page<Email> findAllPageable(PageableRest pageable) {
|
||||
return emailRepository.findAll(PageRequest.of(pageable.getNumber(), pageable.getSize(), pageable.getSort()));
|
||||
}
|
||||
|
||||
public Page<Email> findByPropertyAndPageable(HashMap<String, String> property ,PageableRest pageable){
|
||||
return emailRepository.findByPropertyAndPageable(property, pageable);
|
||||
}
|
||||
|
||||
public Optional<Email> findById(Long id) {
|
||||
return emailRepository.findById(id);
|
||||
}
|
||||
@Transactional
|
||||
public Email save(Email email) {
|
||||
return emailRepository.save(email);
|
||||
}
|
||||
@Transactional
|
||||
public int setStatusForEmail(StatusType status, Long id) {
|
||||
return emailRepository.setStatusForEmail(status, id);
|
||||
}
|
||||
@Transactional
|
||||
public int setIncreaseResendCountForEmail(Integer resend, Long id) {
|
||||
return emailRepository.setIncreaseResendCountForEmail(resend, id);
|
||||
}
|
||||
public List<String> filterRecipient(Email email, RecipientType type) {
|
||||
List<Recipient> rcp = email.getRecipients().stream().filter(x -> x.getType() == type).toList();
|
||||
return rcp.parallelStream().map(Recipient::getRecipient).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.EmailTemplateWithoutAttachment;
|
||||
import com.solvway.services.email.repo.EmailTemplateWithoutAttachmentRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class EmailTemplateWithoutAttachmentService {
|
||||
|
||||
@Autowired
|
||||
private EmailTemplateWithoutAttachmentRepository emailTemplateWithoutAttachmentRepository;
|
||||
|
||||
|
||||
public List<EmailTemplateWithoutAttachment> findByNameAndStatus(String name, TemplateStatusType status) {
|
||||
return emailTemplateWithoutAttachmentRepository.findByNameAndStatus(name,status);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.util.MailGunRestClient;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "email.provider", havingValue = "MAIL_GUN")
|
||||
public class MailGunService implements EmailClientService{
|
||||
private static final Logger log = LoggerFactory.getLogger(MailGunService.class);
|
||||
|
||||
private final MailGunRestClient mailGunRestClient;
|
||||
private final String password;
|
||||
private final String messagesUrl;
|
||||
private final String username;
|
||||
|
||||
@Autowired
|
||||
public MailGunService(MailGunRestClient mailGunRestClient, String mailGunAPIMessagesUrl, String mailGunAPIUsername,
|
||||
String mailGunAPIPassword) {
|
||||
this.mailGunRestClient = mailGunRestClient;
|
||||
this.username = mailGunAPIUsername;
|
||||
this.password = mailGunAPIPassword;
|
||||
this.messagesUrl = mailGunAPIMessagesUrl;
|
||||
}
|
||||
//
|
||||
// public void sendText(Email email, List<Attachment> attch){
|
||||
//// MultiValueMap<String, Object> map = getPostRequestObject(from, to, cc, attch, subject);
|
||||
//// map.add("text", body);
|
||||
// sendEmail(email,attch);
|
||||
// }
|
||||
//
|
||||
// public String sendHTML(Email email, List<Attachment> attch){
|
||||
//// MultiValueMap<String, Object> map = getPostRequestObject(from, to, cc, attch, subject);
|
||||
//// map.add("html", body);
|
||||
//// System.out.print(map);
|
||||
// return sendEmail(email,attch);
|
||||
// }
|
||||
@Override
|
||||
public boolean sendEmail(Email email, List<Attachment> attch){
|
||||
try {
|
||||
String result = mailGunRestClient.sendEmailMessage(this.messagesUrl, email, attch, this.username, this.password);
|
||||
return StringUtils.hasLength(result);
|
||||
}catch(Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.mailjet.client.MailjetClient;
|
||||
import com.mailjet.client.MailjetRequest;
|
||||
import com.mailjet.client.resource.Emailv31;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.MailjetConfig;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "email.provider", havingValue = "MAIL_JET")
|
||||
public class MailJetService implements EmailClientService{
|
||||
private static final Logger log = LoggerFactory.getLogger(MailJetService.class);
|
||||
@Autowired
|
||||
private DriveService driveService;
|
||||
@Autowired
|
||||
private MailjetClient client;
|
||||
@Autowired
|
||||
private MailjetConfig config;
|
||||
|
||||
@Value("${email.sender-name}")
|
||||
private String senderName;
|
||||
@Override
|
||||
public boolean sendEmail(Email email,List<Attachment> attch){
|
||||
try {
|
||||
MailjetRequest request;
|
||||
//MailjetResponse response;
|
||||
JSONArray recipientArr = new JSONArray();
|
||||
for(Recipient r:email.getRecipients()) {
|
||||
recipientArr.put(
|
||||
new JSONObject().put("Email", r.getRecipient())
|
||||
);
|
||||
}
|
||||
JSONArray attachmentArr = new JSONArray();
|
||||
if(attch!=null && !attch.isEmpty()) {
|
||||
for(Attachment a: attch) {
|
||||
byte[] attachmentContentBytes =driveService.loadPrivateFile(a.getBucketFileId());
|
||||
String s = Base64.getEncoder().encodeToString(attachmentContentBytes);
|
||||
attachmentArr.put(
|
||||
new JSONObject()
|
||||
.put("ContentType",a.getFileType())
|
||||
.put("Filename", a.getFileName())
|
||||
.put("Base64Content", s)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if(attch!=null && !attch.isEmpty()) {
|
||||
request = new MailjetRequest(Emailv31.resource).property(Emailv31.MESSAGES,
|
||||
new JSONArray().put(new JSONObject()
|
||||
.put(Emailv31.Message.FROM,
|
||||
new JSONObject()
|
||||
.put("Email", config.mailjetSender)
|
||||
.put("Name", senderName))
|
||||
.put(Emailv31.Message.TO,recipientArr)
|
||||
.put(Emailv31.Message.SUBJECT, email.getSubject())
|
||||
.put(Emailv31.Message.HTMLPART, email.getBody())
|
||||
.put(Emailv31.Message.ATTACHMENTS, attachmentArr)
|
||||
.put(Emailv31.Message.CUSTOMID, "")));
|
||||
|
||||
}else {
|
||||
request = new MailjetRequest(Emailv31.resource).property(Emailv31.MESSAGES,
|
||||
new JSONArray().put(new JSONObject()
|
||||
.put(Emailv31.Message.FROM,
|
||||
new JSONObject()
|
||||
.put("Email", config.mailjetSender)
|
||||
.put("Name", senderName))
|
||||
.put(Emailv31.Message.TO,recipientArr)
|
||||
.put(Emailv31.Message.SUBJECT, email.getSubject())
|
||||
.put(Emailv31.Message.HTMLPART, email.getBody())
|
||||
.put(Emailv31.Message.CUSTOMID, "")));
|
||||
|
||||
}
|
||||
//response = client.post(request);
|
||||
//log.info("response: "+ response.getStatus());
|
||||
client.post(request);
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import com.solvway.services.email.repo.RecipientRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class RecipientService {
|
||||
|
||||
@Autowired
|
||||
private RecipientRepository recipientRepository;
|
||||
|
||||
@Transactional
|
||||
public Recipient save(Recipient recipient) {
|
||||
return recipientRepository.save(recipient);
|
||||
}
|
||||
|
||||
public Optional<Recipient> findById(Long id) {
|
||||
return recipientRepository.findById(id);
|
||||
}
|
||||
|
||||
// @Transactional
|
||||
// public int inactiveByTemplateId(Long templateId){
|
||||
// return recipientRepository.inactiveByTemplateId(RecipientStatusType.N,templateId);
|
||||
// }
|
||||
|
||||
// @Transactional
|
||||
// public List<Recipient> saveAll(List<Recipient> recipients) {
|
||||
// return recipientRepository.saveAll(recipients);
|
||||
// }
|
||||
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.sendgrid.*;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.configuration.SendGridConfig;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "email.provider", havingValue = "SEND_GRID")
|
||||
public class SendGridService implements EmailClientService{
|
||||
private static final Logger log = LoggerFactory.getLogger(SendGridService.class);
|
||||
@Autowired
|
||||
private SendGrid sendGrid;
|
||||
@Autowired
|
||||
private SendGridConfig sendGridConfig;
|
||||
@Autowired
|
||||
private DriveService driveService;
|
||||
|
||||
@Value("${email.sender-name}")
|
||||
private String senderName;
|
||||
|
||||
@Override
|
||||
public boolean sendEmail(Email email,List<Attachment> attch) {
|
||||
com.sendgrid.Email from = new com.sendgrid.Email(sendGridConfig.getSendGridSender(), senderName);
|
||||
String subject =email.getSubject();
|
||||
Content content = new Content("text/html", email.getBody());
|
||||
for(Recipient r:email.getRecipients()) {
|
||||
com.sendgrid.Email to = new com.sendgrid.Email(r.getRecipient());
|
||||
Mail mail = new Mail(from, subject, to, content);
|
||||
try {
|
||||
if(attch!=null && !attch.isEmpty()) {
|
||||
for(Attachment a: attch) {
|
||||
try {
|
||||
Attachments attachments = new Attachments();
|
||||
attachments.setFilename(a.getFileName());
|
||||
attachments.setType("application/pdf");
|
||||
attachments.setDisposition("attachment");
|
||||
byte[] attachmentContentBytes =driveService.loadPrivateFile(a.getBucketFileId());
|
||||
String s = Base64.getEncoder().encodeToString(attachmentContentBytes);
|
||||
attachments.setContent(s);
|
||||
mail.addAttachments(attachments);
|
||||
}catch(Exception e) {
|
||||
log.error("Error when attach file to email: {}", a.getFileName());
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch(Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return false;
|
||||
}
|
||||
Request request = new Request();
|
||||
try {
|
||||
request.setMethod(Method.POST);
|
||||
request.setEndpoint("mail/send");
|
||||
request.setBody(mail.build());
|
||||
sendGrid.api(request);
|
||||
} catch (IOException ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.services.email.model.Sms;
|
||||
|
||||
public interface SmsClientService {
|
||||
Sms sendSms(Sms sms);
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SmsS360Service implements SmsClientService {
|
||||
private final RestTemplate restTemplate;
|
||||
@Value("${sms.smss360.api-key}")
|
||||
private String apiKey;
|
||||
@Value("${sms.smss360.email}")
|
||||
private String email;
|
||||
@Override
|
||||
public Sms sendSms(Sms sms) {
|
||||
String url = "https://www.smss360.com/api/sendsms.php?email=@#;EMAIL@#;&key=@#;KEY@#;&recipient=@#;RECIPIENT@#;&message=@#;MESSAGE@#;&referenceID=@#;REFERENCEID@#;"
|
||||
.replace("@#;EMAIL@#;", email)
|
||||
.replace("@#;KEY@#;", apiKey)
|
||||
.replace("@#;RECIPIENT@#;", sms.getRecipient())
|
||||
.replace("@#;MESSAGE@#;", sms.getContent())
|
||||
.replace("@#;REFERENCEID@#;", sms.getUuid());
|
||||
String response = restTemplate.getForObject(url, String.class);
|
||||
sms.getProviderResponse().add(response);
|
||||
sms.setStatus(processResponse(response));
|
||||
return sms;
|
||||
}
|
||||
private SmsEnum.SmsStatus processResponse(String response) {
|
||||
try {
|
||||
// Creating a DocumentBuilder Object
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder docBuilder = factory.newDocumentBuilder();
|
||||
|
||||
// Parsing the XML Document
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
|
||||
Document xmldoc = docBuilder.parse(input);
|
||||
|
||||
// Normalize the XML structure
|
||||
xmldoc.getDocumentElement().normalize();
|
||||
|
||||
// Retrieving the Root Element
|
||||
Element root = xmldoc.getDocumentElement();
|
||||
//System.out.println("Root element name is " + root.getTagName());
|
||||
|
||||
// Extract statuscode and statusmsg
|
||||
String statusCode = getElementTextContent(root, "statusCode");
|
||||
String statusMsg = getElementTextContent(root, "statusMsg");
|
||||
if("1606".equals(statusCode)){
|
||||
return SmsEnum.SmsStatus.Y;
|
||||
}
|
||||
//System.out.println("Status Code: " + statusCode);
|
||||
//System.out.println("Status Message: " + statusMsg);
|
||||
|
||||
// Extract recipient, balance, referenceID, and part
|
||||
// Element smsElement = (Element) root.getElementsByTagName("sms").item(0);
|
||||
// if (smsElement != null) {
|
||||
// Element itemsElement = (Element) smsElement.getElementsByTagName("items").item(0);
|
||||
// if (itemsElement != null) {
|
||||
// String recipient = getElementTextContent(itemsElement, "recipient");
|
||||
// String balance = getElementTextContent(smsElement, "balance");
|
||||
// String referenceID = getElementTextContent(itemsElement, "referenceID");
|
||||
// String part = getElementTextContent(itemsElement, "part");
|
||||
//
|
||||
// System.out.println("Recipient: " + recipient);
|
||||
// System.out.println("Balance: " + balance);
|
||||
// System.out.println("Reference ID: " + referenceID);
|
||||
// System.out.println("Part: " + part);
|
||||
// }
|
||||
// }
|
||||
|
||||
// Determine SmsStatus based on statusCode
|
||||
// You'll need to implement this logic based on your requirements
|
||||
return SmsEnum.SmsStatus.N;
|
||||
} catch (Exception e) {
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
return SmsEnum.SmsStatus.N;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getElementTextContent(Element parent, String tagName) {
|
||||
NodeList nodeList = parent.getElementsByTagName(tagName);
|
||||
if (nodeList.getLength() > 0) {
|
||||
Node node = nodeList.item(0);
|
||||
if (node != null) {
|
||||
return node.getTextContent();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.enums.SmsEnum;
|
||||
import com.solvway.services.email.model.Sms;
|
||||
import com.solvway.services.email.repo.SmsRepository;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SmsService {
|
||||
private final SmsRepository smsRepository;
|
||||
|
||||
public Page<Sms> findAllPageable(PageableRest pageable) {
|
||||
return smsRepository.findAll(PageRequest.of(pageable.getNumber(), pageable.getSize(), pageable.getSort()));
|
||||
}
|
||||
|
||||
public Page<Sms> findByPropertyAndPageable(HashMap<String, String> property , PageableRest pageable){
|
||||
return smsRepository.findByPropertyAndPageable(property, pageable);
|
||||
}
|
||||
|
||||
public Optional<Sms> findById(Long id) {
|
||||
return smsRepository.findById(id);
|
||||
}
|
||||
|
||||
public Optional<Sms> findByUuid(String uuid) {
|
||||
return smsRepository.findByUuid(uuid);
|
||||
}
|
||||
@Transactional
|
||||
public Sms save(Sms sms) {
|
||||
return smsRepository.save(sms);
|
||||
}
|
||||
@Transactional
|
||||
public int setStatusForSms(SmsEnum.SmsStatus status, Long id) {
|
||||
return smsRepository.setStatusForSms(status, id);
|
||||
}
|
||||
@Transactional
|
||||
public int setIncreaseResendCountForSms(Integer resend, Long id) {
|
||||
return smsRepository.setIncreaseResendCountForSms(resend, id);
|
||||
}
|
||||
@Transactional
|
||||
public int setProviderResponseForSms(List<String> providerResponse, Long id) {
|
||||
return smsRepository.setProviderResponseForSms(providerResponse, id);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.core.enums.EmailEnum.RecipientType;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "email.provider", havingValue = "SMTP")
|
||||
public class SmtpService implements EmailClientService{
|
||||
private static final Logger log = LoggerFactory.getLogger(SmtpService.class);
|
||||
@Autowired
|
||||
public JavaMailSender emailSender;
|
||||
@Autowired
|
||||
private EmailService emailService;
|
||||
@Autowired
|
||||
private DriveService driveService;
|
||||
|
||||
@Value("${email.sender-name}")
|
||||
private String senderName;
|
||||
|
||||
public void sendSimpleMessage(
|
||||
String to, String subject, String text) {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setTo(to);
|
||||
message.setSubject(subject);
|
||||
message.setText(text);
|
||||
emailSender.send(message);
|
||||
}
|
||||
@Override
|
||||
public boolean sendEmail(Email email, List<Attachment> attch) {
|
||||
try {
|
||||
|
||||
MimeMessage message = emailSender.createMimeMessage();
|
||||
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
helper.setFrom(email.getSender(), senderName);
|
||||
helper.setTo(emailService.filterRecipient(email,RecipientType.R).toArray(new String[0]));
|
||||
helper.setSubject(email.getSubject());
|
||||
helper.setText(email.getBody(), true);
|
||||
if(attch!=null && !attch.isEmpty()) {
|
||||
for(Attachment a: attch) {
|
||||
try {
|
||||
byte[] data = driveService.loadPrivateFile(a.getBucketFileId());
|
||||
helper.addAttachment(a.getFileName(), new ByteArrayResource(data));
|
||||
}catch(Exception e) {
|
||||
log.error("Error when attach file to email: "+ a.getFileName());
|
||||
StackTraceUtil.printStackTrace(log, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
|
||||
* helper.addAttachment("Invoice", file);
|
||||
*/
|
||||
|
||||
emailSender.send(message);
|
||||
return true;
|
||||
|
||||
}catch(Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.solvway.services.email.service;
|
||||
|
||||
import com.solvway.core.enums.EmailEnum.TemplateStatusType;
|
||||
import com.solvway.services.email.model.EmailTemplate;
|
||||
import com.solvway.services.email.repo.TemplateRepository;
|
||||
import com.solvway.services.email.util.paging.PageableRest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class TemplateService {
|
||||
|
||||
@Autowired
|
||||
private TemplateRepository templateRepository;
|
||||
|
||||
public Page<EmailTemplate> findAllPageable(PageableRest pageable) {
|
||||
return templateRepository.findAll(PageRequest.of(pageable.getNumber(), pageable.getSize(), pageable.getSort()));
|
||||
}
|
||||
|
||||
public Page<EmailTemplate> findByPropertyAndPageable(HashMap<String, String> property ,PageableRest pageable){
|
||||
return templateRepository.findByPropertyAndPageable(property, pageable);
|
||||
}
|
||||
|
||||
public Optional<EmailTemplate> findById(Long id) {
|
||||
return templateRepository.findById(id);
|
||||
}
|
||||
|
||||
public Optional<EmailTemplate> findByName(String name) {
|
||||
return templateRepository.findByName(name);
|
||||
}
|
||||
|
||||
public List<EmailTemplate> findByNameAndStatus(String name, TemplateStatusType status) {
|
||||
return templateRepository.findByNameAndStatus(name,status);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailTemplate save(EmailTemplate recipient) {
|
||||
return templateRepository.save(recipient);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.solvway.services.email.util;
|
||||
|
||||
import com.mashape.unirest.http.HttpMethod;
|
||||
import com.mashape.unirest.http.Unirest;
|
||||
|
||||
public class CustomUnirest extends Unirest{
|
||||
|
||||
public static CustomeHttpRequestWithBody customPost(String url) {
|
||||
return new CustomeHttpRequestWithBody(HttpMethod.POST, url);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package com.solvway.services.email.util;
|
||||
|
||||
import com.mashape.unirest.http.HttpMethod;
|
||||
import com.mashape.unirest.http.JsonNode;
|
||||
import com.mashape.unirest.http.ObjectMapper;
|
||||
import com.mashape.unirest.http.options.Option;
|
||||
import com.mashape.unirest.http.options.Options;
|
||||
import com.mashape.unirest.request.HttpRequest;
|
||||
import com.mashape.unirest.request.body.MultipartBody;
|
||||
import com.mashape.unirest.request.body.RawBody;
|
||||
import com.mashape.unirest.request.body.RequestBodyEntity;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.service.DriveService;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.mime.content.InputStreamBody;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
|
||||
public class CustomeHttpRequestWithBody extends HttpRequest{
|
||||
|
||||
public CustomeHttpRequestWithBody(HttpMethod method, String url) {
|
||||
super(method, url);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody routeParam(String name, String value) {
|
||||
super.routeParam(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody header(String name, String value) {
|
||||
return (CustomeHttpRequestWithBody) super.header(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody headers(Map<String, String> headers) {
|
||||
return (CustomeHttpRequestWithBody) super.headers(headers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody basicAuth(String username, String password) {
|
||||
super.basicAuth(username, password);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody queryString(Map<String, Object> parameters) {
|
||||
return (CustomeHttpRequestWithBody) super.queryString(parameters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomeHttpRequestWithBody queryString(String name, Object value) {
|
||||
return (CustomeHttpRequestWithBody) super.queryString(name, value);
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, Collection<?> value) {
|
||||
MultipartBody body = new MultipartBody(this).field(name, value);
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, Object value) {
|
||||
return field(name, value, null);
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, File file) {
|
||||
return field(name, file, null);
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, Object value, String contentType) {
|
||||
MultipartBody body = new MultipartBody(this).field(name, (value == null) ? "" : value.toString(), contentType);
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, File file, String contentType) {
|
||||
MultipartBody body = new MultipartBody(this).field(name, file, contentType);
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public MultipartBody fields(Map<String, Object> parameters) {
|
||||
MultipartBody body = new MultipartBody(this);
|
||||
if (parameters != null) {
|
||||
for (Entry<String, Object> param : parameters.entrySet()) {
|
||||
if (param.getValue() instanceof File) {
|
||||
body.field(param.getKey(), (File) param.getValue());
|
||||
} else {
|
||||
body.field(param.getKey(), (param.getValue() == null) ? "" : param.getValue().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, InputStream stream, ContentType contentType, String fileName) {
|
||||
InputStreamBody inputStreamBody = new InputStreamBody(stream, contentType, fileName);
|
||||
MultipartBody body = new MultipartBody(this).field(name, inputStreamBody, true, contentType.toString());
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public MultipartBody field(String name, InputStream stream, String fileName) {
|
||||
MultipartBody body = field(name, stream, ContentType.APPLICATION_OCTET_STREAM, fileName);
|
||||
this.body = body;
|
||||
return body;
|
||||
}
|
||||
|
||||
public RequestBodyEntity body(JsonNode body) {
|
||||
return body(body.toString());
|
||||
}
|
||||
|
||||
public RequestBodyEntity body(String body) {
|
||||
RequestBodyEntity b = new RequestBodyEntity(this).body(body);
|
||||
this.body = b;
|
||||
return b;
|
||||
}
|
||||
|
||||
public RequestBodyEntity body(Object body) {
|
||||
ObjectMapper objectMapper = (ObjectMapper) Options.getOption(Option.OBJECT_MAPPER);
|
||||
|
||||
if (objectMapper == null) {
|
||||
throw new RuntimeException("Serialization Impossible. Can't find an ObjectMapper implementation.");
|
||||
}
|
||||
|
||||
return body(objectMapper.writeValue(body));
|
||||
}
|
||||
|
||||
public RawBody body(byte[] body) {
|
||||
RawBody b = new RawBody(this).body(body);
|
||||
this.body = b;
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sugar method for body operation
|
||||
*
|
||||
* @param body raw org.JSONObject
|
||||
* @return RequestBodyEntity instance
|
||||
*/
|
||||
public RequestBodyEntity body(JSONObject body) {
|
||||
return body(body.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sugar method for body operation
|
||||
*
|
||||
* @param body raw org.JSONArray
|
||||
* @return RequestBodyEntity instance
|
||||
*/
|
||||
public RequestBodyEntity body(JSONArray body) {
|
||||
return body(body.toString());
|
||||
}
|
||||
|
||||
|
||||
public MultipartBody customeAddBody(String str, List<Attachment> list, DriveService driveService) {
|
||||
|
||||
MultipartBody body = null;
|
||||
|
||||
for(Attachment atch: list) {
|
||||
byte[] data = !StringUtils.hasLength(atch.getBucketFileId())? atch.getData(): driveService.loadPrivateFile(atch.getBucketFileId());
|
||||
body = Objects.requireNonNullElseGet(body, () -> new MultipartBody(this)).field(str, data, atch.getFileName());
|
||||
this.body = body;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.solvway.services.email.util;
|
||||
|
||||
import com.mashape.unirest.http.HttpResponse;
|
||||
import com.mashape.unirest.http.Unirest;
|
||||
import com.mashape.unirest.http.exceptions.UnirestException;
|
||||
import com.solvway.core.enums.EmailEnum.RecipientType;
|
||||
import com.solvway.services.email.model.Attachment;
|
||||
import com.solvway.services.email.model.Email;
|
||||
import com.solvway.services.email.model.Recipient;
|
||||
import com.solvway.services.email.service.DriveService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service("mailGunRestClient")
|
||||
public class MailGunRestClient {
|
||||
@Autowired
|
||||
private DriveService driveService;
|
||||
// private RestTemplate restTemplate;
|
||||
//
|
||||
// @Autowired
|
||||
// public MailGunRestClient(RestTemplateBuilder builder) {
|
||||
// this.restTemplate = builder.build();
|
||||
// }
|
||||
//
|
||||
// public Object post(String resourceUrl, MultiValueMap<String, Object> request, String username, String password) {
|
||||
// HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(request,
|
||||
// createHeadersWithUsernamePassword(username, password));
|
||||
// ResponseEntity<String> response = this.restTemplate.exchange(resourceUrl, HttpMethod.POST, requestEntity, String.class);
|
||||
// Object postObject = response.getBody();
|
||||
// return postObject;
|
||||
// }
|
||||
//
|
||||
// private HttpHeaders createHeadersWithUsernamePassword(String username, String password) {
|
||||
// return new HttpHeaders() {
|
||||
// {
|
||||
// String auth = username + ":" + password;
|
||||
// byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
|
||||
// String authHeader = "Basic " + new String(encodedAuth);
|
||||
// set("Accept", MediaType.APPLICATION_JSON.toString());
|
||||
// set("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
|
||||
// set("Authorization", authHeader);
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
|
||||
public String sendEmailMessage(String resourceUrl, Email email, List<Attachment> attch, String username,
|
||||
String password) throws UnirestException {
|
||||
|
||||
if (attch!=null && !attch.isEmpty()) {
|
||||
// send with attachemnt
|
||||
HttpResponse<String> request = CustomUnirest.customPost(resourceUrl).basicAuth("api", password)
|
||||
.customeAddBody("attachment", attch, driveService)
|
||||
.field("from", email.getSender())
|
||||
.field("subject", email.getSubject())
|
||||
.field("html", email.getBody())
|
||||
.field("to",filterRecipient(email, RecipientType.R))
|
||||
.field("cc", filterRecipient(email, RecipientType.CC))
|
||||
.asString();
|
||||
return request.getBody();
|
||||
|
||||
} else {
|
||||
// send without attachemnt
|
||||
HttpResponse<String> request = Unirest.post(resourceUrl).basicAuth("api", password)
|
||||
.field("from", email.getSender())
|
||||
.field("subject", email.getSubject())
|
||||
.field("html", email.getBody())
|
||||
.field("to",filterRecipient(email, RecipientType.R))
|
||||
.field("cc", filterRecipient(email, RecipientType.CC))
|
||||
.asString();
|
||||
return request.getBody();
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> filterRecipient(Email email, RecipientType type) {
|
||||
List<Recipient> rcp = email.getRecipients().stream().filter(x -> x.getType() == type)
|
||||
.toList();
|
||||
return rcp.parallelStream().map(Recipient::getRecipient).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.solvway.services.email.util;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.redis.core.HashOperations;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class RedisUtil<T> {
|
||||
|
||||
@Getter
|
||||
private final RedisTemplate<String, T> redisTemplate;
|
||||
|
||||
private final HashOperations<String, Object, T> hashOperation;
|
||||
|
||||
private final ValueOperations<String, T> valueOperations;
|
||||
|
||||
public RedisUtil(RedisTemplate<String,T> redisTemplate){
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.hashOperation = redisTemplate.opsForHash();
|
||||
this.valueOperations = redisTemplate.opsForValue();
|
||||
}
|
||||
|
||||
public void putMap(String redisKey, Object key, T data) {
|
||||
hashOperation.put(redisKey, key, data);
|
||||
}
|
||||
|
||||
public T getMapAsSingleEntry(String redisKey, Object key) {
|
||||
return hashOperation.get(redisKey, key);
|
||||
}
|
||||
|
||||
public Map<Object, T> getMapAsAll(String redisKey) {
|
||||
return hashOperation.entries(redisKey);
|
||||
}
|
||||
|
||||
public void putValue(String key, T value) {
|
||||
valueOperations.set(key, value);
|
||||
}
|
||||
|
||||
public void putValueWithExpireTime(String key, T value, long timeout, TimeUnit unit) {
|
||||
valueOperations.set(key, value, timeout, unit);
|
||||
}
|
||||
|
||||
public T getValue(String key) {
|
||||
return valueOperations.get(key);
|
||||
}
|
||||
|
||||
public void setExpire(String key, long timeout, TimeUnit unit) {
|
||||
redisTemplate.expire(key, timeout, unit);
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.solvway.services.email.util.paging;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
|
||||
@Getter
|
||||
public class PageableRest {
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class SortRest {
|
||||
public String direction;
|
||||
public String property;
|
||||
|
||||
}
|
||||
|
||||
@Setter
|
||||
public int number;
|
||||
@Setter
|
||||
public int size;
|
||||
public ArrayList<SortRest> sorts;
|
||||
|
||||
public void setSorts(ArrayList<SortRest> sorts) {
|
||||
if(this.sorts==null) {
|
||||
this.sorts = new ArrayList<>();
|
||||
}
|
||||
this.sorts = sorts;
|
||||
}
|
||||
public Sort getSort() {
|
||||
Iterator<SortRest> it = this.sorts.iterator();
|
||||
Sort sort = null;
|
||||
while (it.hasNext()) {
|
||||
SortRest sr = it.next();
|
||||
if(sort == null) {
|
||||
sort = Sort.by(new Order(Direction.valueOf(sr.getDirection()), sr.getProperty()));
|
||||
}else {
|
||||
sort = sort.and(Sort.by(new Order(Direction.valueOf(sr.getDirection()), sr.getProperty())));
|
||||
}
|
||||
}
|
||||
|
||||
return sort;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user