Skip to content

Commit

Permalink
Refractored sms with use of token instead of session and made the pro…
Browse files Browse the repository at this point in the history
…cess async
  • Loading branch information
atishbeehyv123 committed Aug 1, 2023
1 parent cb0581a commit 7529244
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 105 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.bahmni.module.bahmnicore.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {

@Bean(name = "bahmniCoreAsync")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
return threadPoolTaskExecutor;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package org.bahmni.module.bahmnicore.service;

import org.openmrs.api.context.UserContext;
import org.openmrs.module.emrapi.patient.PatientProfile;
import org.springframework.transaction.annotation.Transactional;

public interface RegistrationSmsService {
@Transactional(readOnly = true)
void sendRegistrationSMS(PatientProfile profile,String location,String reportingSessionCookie);
void sendRegistrationSMS(PatientProfile profile, String location, UserContext userContext);
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
package org.bahmni.module.bahmnicore.service.impl;


import org.bahmni.module.bahmnicore.properties.BahmniCoreProperties;
import org.springframework.stereotype.Component;

@Component
public class ConnectionDetails {
private static final String AUTH_URI = "openmrs.auth.uri";
private static final String OPENMRS_USER = "openmrs.user";
private static final String OPENMRS_PASSWORD = "openmrs.password";
private static final String OPENMRS_WEBCLIENT_CONNECT_TIMEOUT = "openmrs.connectionTimeoutInMilliseconds";
private static final String OPENMRS_WEBCLIENT_READ_TIMEOUT = "openmrs.replyTimeoutInMilliseconds";

public static org.bahmni.webclients.ConnectionDetails get() {
return new org.bahmni.webclients.ConnectionDetails(
BahmniCoreProperties.getProperty(AUTH_URI),
BahmniCoreProperties.getProperty(OPENMRS_USER),
BahmniCoreProperties.getProperty(OPENMRS_PASSWORD),
Integer.parseInt(BahmniCoreProperties.getProperty(OPENMRS_WEBCLIENT_CONNECT_TIMEOUT)),
Integer.parseInt(BahmniCoreProperties.getProperty(OPENMRS_WEBCLIENT_READ_TIMEOUT)));
}
}
//package org.bahmni.module.bahmnicore.service.impl;
//
//
//import org.bahmni.module.bahmnicore.properties.BahmniCoreProperties;
//import org.springframework.stereotype.Component;
//
//@Component
//public class ConnectionDetails {
// private static final String AUTH_URI = "openmrs.auth.uri";
// private static final String OPENMRS_USER = "openmrs.user";
// private static final String OPENMRS_PASSWORD = "openmrs.password";
// private static final String OPENMRS_WEBCLIENT_CONNECT_TIMEOUT = "openmrs.connectionTimeoutInMilliseconds";
// private static final String OPENMRS_WEBCLIENT_READ_TIMEOUT = "openmrs.replyTimeoutInMilliseconds";
//
// public static org.bahmni.webclients.ConnectionDetails get() {
// return new org.bahmni.webclients.ConnectionDetails(
// BahmniCoreProperties.getProperty(AUTH_URI),
// BahmniCoreProperties.getProperty(OPENMRS_USER),
// BahmniCoreProperties.getProperty(OPENMRS_PASSWORD),
// Integer.parseInt(BahmniCoreProperties.getProperty(OPENMRS_WEBCLIENT_CONNECT_TIMEOUT)),
// Integer.parseInt(BahmniCoreProperties.getProperty(OPENMRS_WEBCLIENT_READ_TIMEOUT)));
// }
//}
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
package org.bahmni.module.bahmnicore.service.impl;

import java.net.URI;
import java.net.URISyntaxException;

import org.bahmni.module.bahmnicore.service.OpenmrsLogin;
import org.bahmni.webclients.ClientCookies;
import org.bahmni.webclients.HttpClient;
import org.springframework.stereotype.Component;

@Component
public class OpenmrsLoginImpl implements OpenmrsLogin {
private ClientCookies cookies;

@Override
public void getConnection() {
HttpClient authenticatedWebClient = WebClientFactory.getClient();
org.bahmni.webclients.ConnectionDetails connectionDetails = ConnectionDetails.get();
String authUri = connectionDetails.getAuthUrl();
getCookiesAfterConnection(authenticatedWebClient, authUri);
}

public void getCookiesAfterConnection(HttpClient authenticatedWebClient, String urlString) {
try {
this.cookies = authenticatedWebClient.getCookies(new URI(urlString));
} catch (URISyntaxException e) {
throw new RuntimeException("Is not a valid URI - " + urlString);
}
}

@Override
public ClientCookies getCookies() {
return cookies;
}
}
//package org.bahmni.module.bahmnicore.service.impl;
//
//import java.net.URI;
//import java.net.URISyntaxException;
//
//import org.bahmni.module.bahmnicore.service.OpenmrsLogin;
//import org.bahmni.webclients.ClientCookies;
//import org.bahmni.webclients.HttpClient;
//import org.springframework.stereotype.Component;
//
//@Component
//public class OpenmrsLoginImpl implements OpenmrsLogin {
// private ClientCookies cookies;
//
// @Override
// public void getConnection() {
// HttpClient authenticatedWebClient = WebClientFactory.getClient();
// org.bahmni.webclients.ConnectionDetails connectionDetails = ConnectionDetails.get();
// String authUri = connectionDetails.getAuthUrl();
// getCookiesAfterConnection(authenticatedWebClient, authUri);
// }
//
// public void getCookiesAfterConnection(HttpClient authenticatedWebClient, String urlString) {
// try {
// this.cookies = authenticatedWebClient.getCookies(new URI(urlString));
// } catch (URISyntaxException e) {
// throw new RuntimeException("Is not a valid URI - " + urlString);
// }
// }
//
// @Override
// public ClientCookies getCookies() {
// return cookies;
// }
//}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.UserContext;
import org.openmrs.module.emrapi.patient.PatientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -26,8 +28,11 @@ public RegistrationSmsServiceImpl(SMSService smsService) {
}

@Override
@Transactional(readOnly = true)
public void sendRegistrationSMS(PatientProfile profile, String locationUuid, String reportingSessionCookie) {
@Async("bahmniCoreAsync")
public void sendRegistrationSMS(PatientProfile profile, String locationUuid, UserContext userContext) {
Context.openSession();
Context.setUserContext(userContext);
if (Context.getUserContext().hasPrivilege("Send Registration SMS")){
Patient patient = profile.getPatient();
String phoneNumber = patient.getAttribute("phoneNumber").getValue();
if (null == phoneNumber) {
Expand All @@ -36,6 +41,8 @@ public void sendRegistrationSMS(PatientProfile profile, String locationUuid, Str
}
Location location = Context.getLocationService().getLocationByUuid(locationUuid);
String message = smsService.getRegistrationMessage(new Locale("en"), patient, location);
smsService.sendSMS(phoneNumber, message);
smsService.sendSMS(phoneNumber, message);}
else
log.info("SMS not sent because current user does not have the required privileges");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,33 +29,24 @@

@Service
public class SMSServiceImpl implements SMSService {

private OpenmrsLoginImpl openmrsLogin;
private static Logger logger = LogManager.getLogger(BahmniDrugOrderService.class);
private final static String REGISTRATION_SMS_TEMPLATE = "sms.registrationSMSTemplate";
private final static String SMS_URI = "sms.uri";
@Autowired
public SMSServiceImpl(OpenmrsLoginImpl openmrsLogin) {
this.openmrsLogin = openmrsLogin;
}

@Override
public String sendSMS(String phoneNumber, String message) {
try {
SMSRequest smsRequest = new SMSRequest();
smsRequest.setPhoneNumber(phoneNumber);
smsRequest.setMessage(message);

ObjectMapper Obj = new ObjectMapper();
String jsonObject = Obj.writeValueAsString(smsRequest);
StringEntity params = new StringEntity(jsonObject);
String smsUrl = StringUtils.isBlank(BahmniCoreProperties.getProperty("sms.uri")) ? SMS_URI : BahmniCoreProperties.getProperty("sms.uri");
HttpPost request = new HttpPost(smsUrl);
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", "Bearer " +BahmniCoreProperties.getProperty("sms-service.token"));
request.setEntity(params);
openmrsLogin.getConnection();
ClientCookies clientCookies = openmrsLogin.getCookies();
request.setHeader("Cookie","reporting_session="+ clientCookies.entrySet().iterator().next().getValue());
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);
httpClient.close();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
package org.bahmni.module.bahmnicore.service.impl;

import org.bahmni.webclients.ConnectionDetails;
import org.bahmni.webclients.HttpClient;
import org.bahmni.webclients.openmrs.OpenMRSLoginAuthenticator;
import org.springframework.stereotype.Component;

@Component
public class WebClientFactory {

public static HttpClient getClient() {
ConnectionDetails connectionDetails = org.bahmni.module.bahmnicore.service.impl.ConnectionDetails.get();
return new HttpClient(connectionDetails, getAuthenticator(connectionDetails));
}


private static OpenMRSLoginAuthenticator getAuthenticator(ConnectionDetails connectionDetails) {
return new OpenMRSLoginAuthenticator(connectionDetails);

}
}
//package org.bahmni.module.bahmnicore.service.impl;
//
//import org.bahmni.webclients.ConnectionDetails;
//import org.bahmni.webclients.HttpClient;
//import org.bahmni.webclients.openmrs.OpenMRSLoginAuthenticator;
//import org.springframework.stereotype.Component;
//
//@Component
//public class WebClientFactory {
//
// public static HttpClient getaClient() {
// ConnectionDetails connectionDetails = org.bahmni.module.bahmnicore.service.impl.ConnectionDetails.get();
// return new HttpClient(connectionDetails, getAuthenticator(connectionDetails));
// }
//
//
// private static OpenMRSLoginAuthenticator getAuthenticator(ConnectionDetails connectionDetails) {
// return new OpenMRSLoginAuthenticator(connectionDetails);
//
// }
//}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public BahmniPatientProfileResource(EmrPatientProfileService emrPatientProfileSe
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Object> create(@CookieValue(value="bahmni.user.location", required=true) String loginCookie,
@CookieValue(value = "reporting_session", required = true) String reportingSessionCookie,
@RequestHeader(value = "Jump-Accepted", required = false) boolean jumpAccepted,
@RequestBody SimpleObject propertiesToCreate) throws Exception {
List identifiers = ((ArrayList) ((LinkedHashMap) propertiesToCreate.get("patient")).get("identifiers"));
Expand Down Expand Up @@ -125,7 +124,7 @@ public ResponseEntity<Object> create(@CookieValue(value="bahmni.user.location",
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(loginCookie);
String loginlocation = jsonObject.get("uuid").getAsString();
registrationSmsService.sendRegistrationSMS(delegate,loginlocation,reportingSessionCookie);}
registrationSmsService.sendRegistrationSMS(delegate,loginlocation,Context.getUserContext());}
setRelationships(delegate);
return new ResponseEntity<>(ConversionUtil.convertToRepresentation(delegate, Representation.FULL), HttpStatus.OK);
} catch (ContextAuthenticationException e) {
Expand Down
18 changes: 18 additions & 0 deletions bahmnicore-omod/src/main/resources/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,24 @@
<description>Boolean to enable sending email with prescription details</description>
</globalProperty>

<globalProperty>
<property>sms.enableRegistrationSMSAlert</property>
<defaultValue>false</defaultValue>
<description>Boolean to enable sending sms when ptient registers</description>
</globalProperty>

<globalProperty>
<property>clinic.clinicTimings</property>
<defaultValue>Mon-Fri (09:00-22:00), Sat-Sun CLOSED</defaultValue>
<description>Global property having timings of particular clinic</description>
</globalProperty>

<globalProperty>
<property>sms.registrationSMSTemplate</property>
<defaultValue>Thank you for registering at {location}. Please note your Patient Registration Details-{identifier}, name:{patientname}, {gender},Age- {age} years\nFor any queries call us on {helpdesknumber}. Clinic Timings: {facilitytimings}.</defaultValue>
<description>Template of sms being sent when patient registers</description>
</globalProperty>

<globalProperty>
<property>bahmni.executeGroovyObsValueCalculator</property>
<defaultValue>true</defaultValue>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public void shouldReturnHttpPreconditionFailedStatusAndJumpSizeIfIdentifierIsPas
LinkedHashMap identifierProperties = (LinkedHashMap) ((ArrayList) ((LinkedHashMap) propertiesToCreate.get("patient")).get("identifiers")).get(0);
String identifier = String.valueOf(identifierProperties.get("identifierPrefix")).concat("300020");
identifierProperties.put("identifier", identifier);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);
assertEquals(412, response.getStatusCode().value());
assertEquals("[{\"sizeOfJump\":10,\"identifierType\":\"81433852-3f10-11e4-adec-0800271c1b75\"}]", response.getBody().toString());
verify(identifierSourceServiceWrapper,never()).saveSequenceValueUsingIdentifierSourceUuid(anyLong(), anyString());
Expand All @@ -84,7 +84,7 @@ public void shouldCreatePatientWhenUserAcceptsTheJump() throws Exception {
LinkedHashMap identifierProperties = (LinkedHashMap) ((ArrayList) ((LinkedHashMap) propertiesToCreate.get("patient")).get("identifiers")).get(0);
String identifier = String.valueOf(identifierProperties.get("identifierPrefix")).concat("300020");
identifierProperties.put("identifier", identifier);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,true, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,true, propertiesToCreate);
assertEquals(200, response.getStatusCode().value());
}

Expand All @@ -93,13 +93,13 @@ public void shouldCreatePatientWhenIdentifierIsPassedAndJumpIsZero() throws Exce
LinkedHashMap identifierProperties = (LinkedHashMap) ((ArrayList) ((LinkedHashMap) propertiesToCreate.get("patient")).get("identifiers")).get(0);
String identifier = String.valueOf(identifierProperties.get("identifierPrefix")).concat("300010");
identifierProperties.put("identifier", identifier);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);
assertEquals(200, response.getStatusCode().value());
}

@Test
public void shouldCreatePatient() throws Exception {
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);
assertEquals(200, response.getStatusCode().value());
}

Expand All @@ -110,7 +110,7 @@ public void shouldCreatePatientWhenIdentifierPrefixIsNotPresentAndIdentifierIsMa
identifiers.get(0).put("identifier", "identifier");
identifiers.get(0).put("identifierPrefix", "");

ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);

assertEquals(200, response.getStatusCode().value());
}
Expand All @@ -125,7 +125,7 @@ public void shouldCreatePatientWhenIdentifierPrefixIsBlankAndNoIdentifierIsEnter
identifiers.get(0).put("identifierPrefix", "");


ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);

assertEquals(200, response.getStatusCode().value());
}
Expand All @@ -134,7 +134,7 @@ public void shouldCreatePatientWhenIdentifierPrefixIsBlankAndNoIdentifierIsEnter
public void shouldReturnBadRequestForInvalidJson() throws Exception {
LinkedHashMap person = ((LinkedHashMap)((LinkedHashMap)propertiesToCreate.get("patient")).get("person"));
person.remove("names");
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);
assertEquals(400, response.getStatusCode().value());
}

Expand Down Expand Up @@ -170,14 +170,14 @@ public void shouldReturnBadRequestForLongNumericPatientIdentifier() throws Excep
LinkedHashMap identifier = (LinkedHashMap) ((ArrayList) ((LinkedHashMap) propertiesToCreate.get("patient")).get("identifiers")).get(0);
identifier.put("identifier", "BAH12345678912345678");
when(identifierSourceServiceWrapper.saveSequenceValueUsingIdentifierSourceUuid(12345678912345679L, "dead-cafe")).thenThrow(DataException.class);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,true, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,true, propertiesToCreate);
assertThat(response.getStatusCode().value(), is(400));
assertThat(response.getBody().toString(), is("{\"error\":{\"message\":\"Entered numeric patient identifier is too large\"}}"));
}

@Test
public void shouldCreatePatientWithMultipleIdentifiers() throws Exception {
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResource.create(null,false, propertiesToCreate);
assertEquals(200, response.getStatusCode().value());
assertEquals(2, ((PatientProfile)response.getBody()).getPatient().getIdentifiers().size());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public void createPatient() throws Exception {
List<Relationship> relationships = Arrays.asList();
when(personService.getRelationshipsByPerson(person)).thenReturn(relationships);

ResponseEntity<Object> response = bahmniPatientProfileResourceSpy.create(null,null,false, propertiesToCreate);
ResponseEntity<Object> response = bahmniPatientProfileResourceSpy.create(null,false, propertiesToCreate);

Assert.assertEquals(200, response.getStatusCode().value());
verify(identifierSourceServiceWrapper, times(1)).generateIdentifierUsingIdentifierSourceUuid("dead-cafe", "");
Expand Down

0 comments on commit 7529244

Please sign in to comment.