Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.gson.annotations.Expose;
import com.iemr.common.data.beneficiary.Beneficiary;
Expand Down Expand Up @@ -234,9 +232,6 @@ public class BeneficiaryCall {
@Expose
@Column(name = "InsName")
private String instName;

@Value("${cti-logger_base_url}")
private String loggerBaseURL;

@Transient
@Expose
Expand Down Expand Up @@ -282,17 +277,6 @@ public BeneficiaryCall(Long beneficiaryRegID, Boolean is1097, String createdBy)
this.createdBy = createdBy;
}

public BeneficiaryCall(Long benCallID, Timestamp createdDate, String agentID, String callID, String recordingPath,
String archivePath) {
// String loggerBaseURL = ConfigProperties.getPropertyByName("cti-logger_base_url");
this.benCallID = benCallID;
this.createdDate = createdDate;
this.agentID = agentID;
this.callID = callID;
this.recordingPath = (recordingPath != null) ? (loggerBaseURL + "/" + recordingPath) : recordingPath;
this.archivePath = (archivePath != null) ? (loggerBaseURL + "/" + archivePath) : archivePath;
}

@Transient
private OutputMapper outputMapper = new OutputMapper();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,11 @@ public String save(BeneficiaryModel beneficiaryModel, HttpServletRequest servlet

try {
logger.info("[SMS] Attempting to send welcome SMS to: " + phoneNo);
String smsResult = welcomeBenificarySmsService.sendWelcomeSMStoBenificiary(
welcomeBenificarySmsService.sendWelcomeSMStoBenificiary(
phoneNo,
beneficiaryName.trim(),
beneficiary.getBeneficiaryID()
);
logger.info("[SMS] Result: " + smsResult);
} catch (Exception smsError) {
// SMS failed but beneficiary is already created - don't fail the request
logger.warn("[SMS] Failed to send SMS: " + smsError.getMessage() +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@

String updateNotificationType(String request) throws JSONException, IEMRException;

String getEmergencyContacts(String request) throws IEMRException;
String getEmergencyContacts(String request) throws IEMRException, JsonMappingException, JsonProcessingException;

Check warning on line 49 in src/main/java/com/iemr/common/service/notification/NotificationService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the declaration of thrown exception 'com.fasterxml.jackson.databind.JsonMappingException' which is a subclass of 'com.fasterxml.jackson.core.JsonProcessingException'.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gFjCb8NoYRngNWc&open=AaF71gFjCb8NoYRngNWc&pullRequest=462

String getSupervisorEmergencyContacts(String request) throws IEMRException, JsonMappingException, JsonProcessingException;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,10 +437,12 @@
}

@Override
public String getEmergencyContacts(String request) throws IEMRException
public String getEmergencyContacts(String request) throws IEMRException, JsonMappingException, JsonProcessingException

Check warning on line 440 in src/main/java/com/iemr/common/service/notification/NotificationServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the declaration of thrown exception 'com.fasterxml.jackson.databind.JsonMappingException' which is a subclass of 'com.fasterxml.jackson.core.JsonProcessingException'.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gHtCb8NoYRngNWd&open=AaF71gHtCb8NoYRngNWd&pullRequest=462
{
List<EmergencyContacts> emergencyContacts = new ArrayList<EmergencyContacts>();
EmergencyContacts emergencyContactRequest = inputMapper.gson().fromJson(request, EmergencyContacts.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
EmergencyContacts emergencyContactRequest = objectMapper.readValue(request, EmergencyContacts.class);
Integer providerServiceMapID = emergencyContactRequest.getProviderServiceMapID();
Integer notificationTypeID = emergencyContactRequest.getNotificationTypeID();
// emergencyContacts = emergencyContactsRepository.getEmergencyContacts(providerServiceMapID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

@Service
public interface WelcomeBenificarySmsService {
public String sendWelcomeSMStoBenificiary(String contactNo,String beneficiaryName,String beneficiaryId);
public void sendWelcomeSMStoBenificiary(String contactNo,String beneficiaryName,String beneficiaryId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
private String smsTemplate =null;

@Async
public String sendWelcomeSMStoBenificiary(String contactNo, String beneficiaryName, String beneficiaryId) {
public void sendWelcomeSMStoBenificiary(String contactNo, String beneficiaryName, String beneficiaryId) {

try {
String sendSMSAPI = SMS_GATEWAY_URL;
Expand Down Expand Up @@ -87,18 +87,16 @@
ResponseEntity<String> response = restTemplate.postForEntity(sendSMSAPI, request, String.class);
logger.info("sms-response:" + response.getBody());
if (response.getStatusCode().value() == 200) {
return "OTP sent successfully on register mobile number";
logger.info("[SMS] Welcome SMS sent to " + contactNo);

Check warning on line 90 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use the built-in formatting to construct this argument.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWW&open=AaF71gDVCb8NoYRngNWW&pullRequest=462

Check warning on line 90 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Format specifiers should be used instead of string concatenation.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWZ&open=AaF71gDVCb8NoYRngNWZ&pullRequest=462
} else {
return "Fail";

logger.warn("[SMS] Welcome SMS failed for " + contactNo + " with status " + response.getStatusCode());

Check warning on line 92 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use the built-in formatting to construct this argument.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWX&open=AaF71gDVCb8NoYRngNWX&pullRequest=462

Check warning on line 92 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Format specifiers should be used instead of string concatenation.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWa&open=AaF71gDVCb8NoYRngNWa&pullRequest=462
}
} else {
logger.warn("[SMS] Welcome SMS not sent: SMS template '" + smsTemplateName + "' not found");

Check warning on line 95 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Format specifiers should be used instead of string concatenation.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWb&open=AaF71gDVCb8NoYRngNWb&pullRequest=462

Check warning on line 95 in src/main/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use the built-in formatting to construct this argument.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF71gDVCb8NoYRngNWY&open=AaF71gDVCb8NoYRngNWY&pullRequest=462
}

}
catch (Exception e) {
return "Error sending SMS: " + e.getMessage().toString();
} catch (Exception e) {
logger.error("[SMS] Error sending welcome SMS to " + contactNo + ": " + e.getMessage(), e);
}
return null;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ void sendNotificationReturnsMessageId() {
NotificationMessage message = new NotificationMessage();
when(firebaseNotificationService.sendNotification(message)).thenReturn("projects/amrit/messages/1");

assertThat(controller.sendNotificationByToken(message)).isEqualTo("projects/amrit/messages/1");
assertThat(controller.sendNotificationByToken(message).getBody()).isEqualTo("projects/amrit/messages/1");
}

@Test
Expand All @@ -41,7 +41,7 @@ void updateTokenReturnsConfirmation() {
UserToken userToken = new UserToken();
when(firebaseNotificationService.updateToken(userToken)).thenReturn("Save Successfully");

assertThat(controller.updateToken(userToken)).isEqualTo("Save Successfully");
assertThat(controller.updateToken(userToken).getBody()).isEqualTo("Save Successfully");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.iemr.common.data.userToken.UserTokenData;
import com.iemr.common.data.userToken.UserFcmTokenData;
import com.iemr.common.model.notification.NotificationMessage;
import com.iemr.common.model.notification.UserToken;
import com.iemr.common.repo.userToken.UserTokenRepo;
import com.iemr.common.repo.userToken.UserFcmTokenRepo;
import com.iemr.common.utils.CookieUtil;
import com.iemr.common.utils.JwtUtil;

Expand All @@ -45,7 +45,7 @@
class FirebaseNotificationServiceTest {

@Mock
private UserTokenRepo userTokenRepo;
private UserFcmTokenRepo userTokenRepo;
@Mock
private CookieUtil cookieUtil;
@Mock
Expand Down Expand Up @@ -78,7 +78,7 @@ private NotificationMessage notification() {
@Test
@DisplayName("no configured Firebase messaging means the notification is skipped, not attempted")
void notificationIsSkippedWhenFirebaseIsNotConfigured() {
assertThat(service.sendNotification(notification())).isNull();
assertThat(service.sendNotification(notification())).isEqualTo("FirebaseMessaging bean is not initialized.");
}

@Test
Expand All @@ -101,48 +101,49 @@ void notificationIsPublishedToTopic() throws Exception {
void deliveryFailureIsReported() throws Exception {
FirebaseMessaging messaging = mock(FirebaseMessaging.class);
ReflectionTestUtils.setField(service, "firebaseMessaging", messaging);
when(messaging.send(any(Message.class))).thenThrow(mock(FirebaseMessagingException.class));
FirebaseMessagingException failure = mock(FirebaseMessagingException.class);
when(failure.getMessage()).thenReturn("token not registered");
when(messaging.send(any(Message.class))).thenThrow(failure);

try (MockedStatic<FirebaseMessaging> statics = mockStatic(FirebaseMessaging.class)) {
statics.when(FirebaseMessaging::getInstance).thenReturn(messaging);

assertThat(service.sendNotification(notification())).isEqualTo("Error sending notification");
assertThat(service.sendNotification(notification())).isEqualTo("FCM Error : token not registered");
}
}

@Test
@DisplayName("an existing device token is updated in place")
void existingTokenIsUpdated() {
UserTokenData existing = new UserTokenData();
UserFcmTokenData existing = new UserFcmTokenData();
existing.setUserId(7);
existing.setToken("old-token");
when(userTokenRepo.findById(7)).thenReturn(Optional.of(existing));
when(userTokenRepo.findByUserId(7)).thenReturn(Optional.of(existing));

UserToken userToken = new UserToken();
userToken.setUserId(7);
userToken.setToken("new-token");

assertThat(service.updateToken(userToken)).isEqualTo("Save Successfully");

ArgumentCaptor<UserTokenData> captor = ArgumentCaptor.forClass(UserTokenData.class);
ArgumentCaptor<UserFcmTokenData> captor = ArgumentCaptor.forClass(UserFcmTokenData.class);
verify(userTokenRepo).save(captor.capture());
assertThat(captor.getValue()).isSameAs(existing);
assertThat(captor.getValue().getToken()).isEqualTo("new-token");
assertThat(captor.getValue().getUpdatedAt()).isNotNull();
}

@Test
@DisplayName("a user with no stored token gets a new row")
void newTokenIsCreated() {
when(userTokenRepo.findById(8)).thenReturn(Optional.empty());
when(userTokenRepo.findByUserId(8)).thenReturn(Optional.empty());

UserToken userToken = new UserToken();
userToken.setUserId(8);
userToken.setToken("fresh-token");

assertThat(service.updateToken(userToken)).isEqualTo("Save Successfully");

ArgumentCaptor<UserTokenData> captor = ArgumentCaptor.forClass(UserTokenData.class);
ArgumentCaptor<UserFcmTokenData> captor = ArgumentCaptor.forClass(UserFcmTokenData.class);
verify(userTokenRepo).save(captor.capture());
assertThat(captor.getValue().getUserId()).isEqualTo(8);
assertThat(captor.getValue().getToken()).isEqualTo("fresh-token");
Expand All @@ -154,7 +155,7 @@ void storedTokenIsResolvedFromTheJwtCookie() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
when(jwtUtil.getUserIdFromToken("jwt-value")).thenReturn("11");
UserTokenData stored = new UserTokenData();
UserFcmTokenData stored = new UserFcmTokenData();
stored.setToken("device-token");
when(userTokenRepo.findById(11)).thenReturn(Optional.of(stored));

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.iemr.common.service.welcomeSms;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
Expand Down Expand Up @@ -73,9 +74,7 @@
(mock, context) -> when(mock.postForEntity(anyString(), any(), eq(String.class)))
.thenReturn(new ResponseEntity<>("queued", HttpStatus.OK)))) {

String result = service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42");

assertThat(result).isEqualTo("OTP sent successfully on register mobile number");
service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42");

RestTemplate restTemplate = construction.constructed().get(0);
@SuppressWarnings("unchecked")
Expand All @@ -94,29 +93,32 @@
}

@Test
@DisplayName("a non-200 gateway reply is reported as a failure")
void nonOkGatewayReplyIsAFailure() {
@DisplayName("a non-200 gateway reply is logged rather than thrown")
void nonOkGatewayReplyIsNotThrown() {
stubTemplate("Welcome $$BENE_NAME$$");

try (MockedConstruction<RestTemplate> construction = mockConstruction(RestTemplate.class,
(mock, context) -> when(mock.postForEntity(anyString(), any(), eq(String.class)))
.thenReturn(new ResponseEntity<>("rejected", HttpStatus.ACCEPTED)))) {

assertThat(service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42")).isEqualTo("Fail");
assertThatCode(() -> service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42"))
.doesNotThrowAnyException();
org.mockito.Mockito.verify(construction.constructed().get(0)).postForEntity(anyString(), any(),

Check warning on line 106 in src/test/java/com/iemr/common/service/welcomeSms/WelcomeBenificarySmsServiceImplTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use a static import for "verify".

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AaF88r0gCRnYTt1RJ2SN&open=AaF88r0gCRnYTt1RJ2SN&pullRequest=462
eq(String.class));
}
}

@Test
@DisplayName("a gateway error is reported with its message rather than thrown")
@DisplayName("a gateway error is logged rather than thrown")
void gatewayErrorIsReported() {
stubTemplate("Welcome $$BENE_NAME$$");

try (MockedConstruction<RestTemplate> construction = mockConstruction(RestTemplate.class,
(mock, context) -> when(mock.postForEntity(anyString(), any(), eq(String.class)))
.thenThrow(new RestClientException("gateway unreachable")))) {

assertThat(service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42"))
.isEqualTo("Error sending SMS: gateway unreachable");
assertThatCode(() -> service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42"))
.doesNotThrowAnyException();
}
}

Expand All @@ -126,7 +128,7 @@
when(smsTemplateRepository.findBySmsTemplateName("welcome_sms")).thenReturn(Optional.empty());

try (MockedConstruction<RestTemplate> construction = mockConstruction(RestTemplate.class)) {
assertThat(service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42")).isNull();
service.sendWelcomeSMStoBenificiary("9999999999", "Latha", "BEN-42");
org.mockito.Mockito.verifyNoInteractions(construction.constructed().get(0));
}
}
Expand Down
Loading