Skip to content

Commit

Permalink
Merge pull request #19 from ProjectEKA/auto-response
Browse files Browse the repository at this point in the history
Dheeraj/Ritik/Neeraj | Implement auto response for requests
  • Loading branch information
dheeraj-p authored Aug 31, 2020
2 parents 7ba9359 + 0ea1a88 commit 908d5c7
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.reactive.ClientHttpConnector;
Expand All @@ -33,6 +32,9 @@
import org.springframework.web.reactive.function.client.WebClient;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

Expand Down Expand Up @@ -94,7 +96,7 @@ public ClientErrorExceptionHandler clientErrorExceptionHandler(ErrorAttributes e
@SneakyThrows
@ConditionalOnProperty(value = "devservice.googleservice.enabled", havingValue = "true")
@Bean({"credential"})
public Credential credential(GoogleServiceProperties googleServiceProperties){
public Credential credential(GoogleServiceProperties googleServiceProperties) {
List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
return GoogleCredential.fromStream(new FileInputStream(googleServiceProperties.getCredentialPath()))
.createScoped(SCOPES);
Expand All @@ -103,18 +105,28 @@ public Credential credential(GoogleServiceProperties googleServiceProperties){
@SneakyThrows
@ConditionalOnProperty(value = "devservice.googleservice.enabled", havingValue = "false", matchIfMissing = true)
@Bean({"credential"})
public Credential credentialDisabled(){
public Credential credentialDisabled() {
return new GoogleCredential();
}

@ConditionalOnProperty(value = "devservice.email.autoResponseEnabled", havingValue = "true")
@Bean("autoResponseEmailBody")
public String autoResponseEmailBody(EmailProperties emailProperties) throws IOException {
return Files.readString(Paths.get(emailProperties.getAutoResponseBodyPath()));
}

@ConditionalOnProperty(value = "devservice.email.autoResponseEnabled", havingValue = "false", matchIfMissing = true)
@Bean("autoResponseEmailBody")
public String autoResponseEmptyBody() {
return "";
}

@Bean
public EmailService emailService(@Autowired JavaMailSender javaMailSender,
EmailProperties emailProperties,
GoogleServiceProperties googleServiceProperties,
@Qualifier("credential") Credential credential){
return new EmailService(javaMailSender, emailProperties, googleServiceProperties, credential);
@Qualifier("credential") Credential credential,
@Qualifier("autoResponseEmailBody") String autoResponseEmailBody) {
return new EmailService(javaMailSender, emailProperties, googleServiceProperties, credential, autoResponseEmailBody);
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

import in.projecteka.devservice.email.model.Field;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import javax.validation.Valid;

Expand All @@ -21,7 +24,11 @@ public class EmailController {

@CrossOrigin(origins = "${devservice.email.allowedOrigin}")
@PostMapping(PATH_EMAIL_SEND)
@ResponseStatus(HttpStatus.ACCEPTED)
public Mono<Void> bridgeEntry(@Valid @RequestBody List<Field> emailRequest) {
return emailService.sendEmail(emailRequest);
emailService.processRequest(emailRequest)
.subscribeOn(Schedulers.newSingle("thread"))
.subscribe();
return Mono.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ public class EmailProperties {
private String sender;
private String receiver;
private String subject;
private String autoResponseBodyPath;
private String autoResponseSubject;
private boolean autoResponseEnabled;
}
90 changes: 59 additions & 31 deletions src/main/java/in/projecteka/devservice/email/EmailService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@
import in.projecteka.devservice.clients.ClientError;
import in.projecteka.devservice.email.model.Field;
import lombok.AllArgsConstructor;
import org.springframework.mail.SimpleMailMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import reactor.core.publisher.Mono;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
Expand All @@ -22,60 +28,82 @@

@AllArgsConstructor
public class EmailService {
private static Logger logger = LoggerFactory.getLogger(EmailService.class);
private JavaMailSender javaMailSender;
private EmailProperties emailProperties;
private GoogleServiceProperties googleServiceProperties;
private Credential credential;
private String autoResponseEmailBody;

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

public Mono<Void> sendEmail(List<Field> emailFormFields) {
public Mono<Void> processRequest(List<Field> emailFormFields) {
return Mono.create(monoSink -> {
try {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(emailProperties.getReceiver());
msg.setFrom(emailProperties.getSender());
msg.setSubject(emailProperties.getSubject());
String body = String.format("Please find the details \n\n" +
"%s \n\n" +
"Regards\n" +
"%s", generateMessage(emailFormFields), emailProperties.getSender());
sendEmail(emailProperties.getReceiver(), emailProperties.getSubject(), body, false);

msg.setText(String.format("Please find the details \n\n" +
"%s \n\n" +
"Regards\n" +
"%s", generateMessage(emailFormFields),emailProperties.getSender() ));

javaMailSender.send(msg);
if(googleServiceProperties.getEnabled()){
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = googleServiceProperties.getSheetId();
final String range = "Data!A1:B1";
List<Object> newRow = emailFormFields.stream().map(Field::getValue).collect(Collectors.toList());
newRow.add(0, getFormattedDate());
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.build();
ValueRange newRecord = new ValueRange()
.setRange(range)
.setValues(List.of(newRow));

service.spreadsheets().values()
.append(spreadsheetId, range, newRecord)
.setValueInputOption("USER_ENTERED")
.execute();
if (emailProperties.isAutoResponseEnabled()) {
sendAutoResponse(extractEmail(emailFormFields));
}
if (googleServiceProperties.getEnabled()) {
insertEntryInSheet(emailFormFields);
}

monoSink.success();
} catch (Exception e) {
logger.error("Error Occurred -->", e);
monoSink.error(ClientError.emailSendingFailed());
}
});
}

private String generateMessage(List<Field> fields){
private String extractEmail(List<Field> emailFormFields) {
return emailFormFields.stream().filter(field -> field.getTag().equals("email")).findFirst().get().getValue();
}

private void sendAutoResponse(String to) throws MessagingException {
sendEmail(to, emailProperties.getAutoResponseSubject(), autoResponseEmailBody, true);
}

private void insertEntryInSheet(List<Field> emailFormFields) throws GeneralSecurityException, IOException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = googleServiceProperties.getSheetId();
final String range = "Data!A1:B1";
List<Object> newRow = emailFormFields.stream().map(Field::getValue).collect(Collectors.toList());
newRow.add(0, getFormattedDate());
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.build();
ValueRange newRecord = new ValueRange()
.setRange(range)
.setValues(List.of(newRow));

service.spreadsheets().values()
.append(spreadsheetId, range, newRecord)
.setValueInputOption("USER_ENTERED")
.execute();
}

private void sendEmail(String to, String subject, String body, boolean isHTML) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
messageHelper.setTo(to);
messageHelper.setFrom(emailProperties.getSender());
messageHelper.setSubject(subject);
messageHelper.setText(body, isHTML);
javaMailSender.send(message);
}

private String generateMessage(List<Field> fields) {
return fields.stream()
.map(f -> String.format("%s: %s", f.getTitle(),
f.getValue()))
.collect(Collectors.joining("\n"));
}

private String getFormattedDate(){
private String getFormattedDate() {
ZonedDateTime istTime = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss ");
return istTime.format(formatter2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@
public class Field {
private String title;
private String value;
private String tag;
}
3 changes: 3 additions & 0 deletions src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ devservice:
sender: xyz@gmail.com
receiver: xyz@gmail.com
subject: Details
autoResponseBodyPath: /Users/some_user/Documents/emailbody.txt
autoResponseSubject: Thanks
autoResponseEnabled: false
googleservice:
credentialPath: /PATH/TO/CREDENTIALS
sheetId: 1CWgChfwZCTtQAdMGi1k7T5-dM8K2pKtp-odJ4p7RxlM
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ devservice:
receiver: ${EMAIL_RECEIVER}
subject: ${EMAIL_SUBJECT}
allowedOrigin: ${ALLOWED_ORIGIN_HOST:*}
autoResponseBodyPath: ${AUTO_RESPONSE_BODY_PATH}
autoResponseSubject: ${AUTO_RESPONSE_SUBJECT}
autoResponseEnabled: ${AUTO_RESPONSE_ENABLED:false}
googleservice:
credentialPath: ${GOOGLE_SERVICE_CREDENTIAL_PATH}
sheetId: ${GOOGLE_SERVICE_SHEET_ID}
Expand Down

0 comments on commit 908d5c7

Please sign in to comment.