From 78cc42dfa793686cfb885a325c999148ddd92ee3 Mon Sep 17 00:00:00 2001 From: Maimoona Kausar Date: Thu, 8 Sep 2016 19:13:53 +0500 Subject: [PATCH] MK: Refactorings --- assets/config/opensrp.properties | 2 +- build/maven.properties | 10 +- .../CustomCertificateSSLSocketFactory.java | 2 +- .../org/opensrp/common/util/DateUtil.java | 15 ++- .../org/opensrp/common/util/HttpResponse.java | 13 +- .../org/opensrp/common/util}/HttpUtil.java | 59 ++++++--- .../opensrp/common/util/RequestMethod.java | 5 + .../common/util}/SecureSocketFactory.java | 2 +- .../connector/openmrs/EncounterAtomfeed.java | 8 +- .../connector/openmrs/PatientAtomfeed.java | 17 ++- .../openmrs/constants/OpenmrsConstants.java | 14 +- .../schedule/OpenmrsSyncerListener.java | 124 ++++++++++++------ .../openmrs/service/EncounterService.java | 4 +- .../openmrs/service/HouseholdService.java | 2 +- .../service/OpenmrsLocationService.java | 2 +- .../service/OpenmrsReportingService.java | 2 +- .../service/OpenmrsSchedulerService.java | 2 +- .../openmrs/service/OpenmrsService.java | 2 +- .../openmrs/service/OpenmrsUserService.java | 2 +- .../openmrs/service/PatientService.java | 49 ++++++- .../service/OpenmrsUserServiceTest.java | 2 +- .../openmrs/service/PatientTest.java | 8 +- .../main/java/org/opensrp/domain/Address.java | 26 ++-- .../org/opensrp/domain/BaseDataObject.java | 25 ++-- .../main/java/org/opensrp/domain/Client.java | 15 +++ .../java/org/opensrp/domain/ErrorTrace.java | 15 ++- .../main/java/org/opensrp/domain/Event.java | 2 + .../org/opensrp/repository/lucene/Query.java | 4 +- .../org/opensrp/service/ClientService.java | 10 +- .../opensrp/service/ErrorTraceService.java | 3 +- .../org/opensrp/service/EventService.java | 6 +- .../FormSubmissionListener.java | 3 +- .../it/AllBaseEntitiesIntegrationTest.java | 4 +- .../it/AllClientsIntegrationTest.java | 16 ++- .../it/AllErrorTraceIntegrationTest.java | 3 +- .../it/AllLocationsIntegrationTest.java | 3 +- .../{router => }/ActionServiceTest.java | 22 ++-- .../test-applicationContext-opensrp.xml | 4 +- .../web/controller/ActionController.java | 113 +++++++++++++++- .../listener/ApplicationStartupListener.java | 6 +- .../web/controller/ActionControllerTest.java | 2 +- 41 files changed, 452 insertions(+), 176 deletions(-) rename {opensrp-connector/src/main/java/org/opensrp/connector => opensrp-common/src/main/java/org/opensrp/common/util}/CustomCertificateSSLSocketFactory.java (95%) rename {opensrp-connector/src/main/java/org/opensrp/connector => opensrp-common/src/main/java/org/opensrp/common/util}/HttpUtil.java (68%) create mode 100644 opensrp-common/src/main/java/org/opensrp/common/util/RequestMethod.java rename {opensrp-connector/src/main/java/org/opensrp/connector => opensrp-common/src/main/java/org/opensrp/common/util}/SecureSocketFactory.java (95%) rename opensrp-core/src/test/java/org/opensrp/scheduler/{router => }/ActionServiceTest.java (88%) diff --git a/assets/config/opensrp.properties b/assets/config/opensrp.properties index 5b962c4078..6fca6f4908 100644 --- a/assets/config/opensrp.properties +++ b/assets/config/opensrp.properties @@ -16,7 +16,7 @@ mcts-report-delay-in-days=10 mcts.poll.time.interval.in.minutes=10 # OpenMRS configuration -openmrs.url=http://localhost:8181/openmrs/ +openmrs.url=http://localhost:8383/openmrs/ openmrs.username=admin openmrs.password=Admin123 diff --git a/build/maven.properties b/build/maven.properties index 68d6a6d379..7d32d346eb 100644 --- a/build/maven.properties +++ b/build/maven.properties @@ -1,10 +1,10 @@ #database configuration that is not likely to change unless massive refactoring -couchdb.db.opensrp=opensrp -couchdb.db.form=opensrp-form +couchdb.db.opensrp=a-opensrp +couchdb.db.form=a-opensrp-form couchdb.db.atomfeed=atomfeed -couchdb.db.mcts=opensrp-mcts -couchdb.db.motech-scheduletracking=motech-scheduletracking-api -couchdb.db.error=opensrp-errortrace +couchdb.db.mcts=a-opensrp-mcts +couchdb.db.motech-scheduletracking=a-motech-scheduletracking-api +couchdb.db.error=a-opensrp-errortrace db.quartz=motechquartz diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/CustomCertificateSSLSocketFactory.java b/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java similarity index 95% rename from opensrp-connector/src/main/java/org/opensrp/connector/CustomCertificateSSLSocketFactory.java rename to opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java index 48cc288d64..1beda5bff4 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/CustomCertificateSSLSocketFactory.java +++ b/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java @@ -1,4 +1,4 @@ -package org.opensrp.connector; +package org.opensrp.common.util; import java.io.IOException; import java.net.Socket; diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/DateUtil.java b/opensrp-common/src/main/java/org/opensrp/common/util/DateUtil.java index 4b56ae5b31..443b5cf339 100644 --- a/opensrp-common/src/main/java/org/opensrp/common/util/DateUtil.java +++ b/opensrp-common/src/main/java/org/opensrp/common/util/DateUtil.java @@ -14,7 +14,6 @@ public class DateUtil { private static DateUtility dateUtility = new RealDate(); - static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); public static DateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd"); public static DateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static DateFormat yyyyMMddTHHmmssSSSZ = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); @@ -46,16 +45,20 @@ private static DateTime toTime(LocalDate referenceDateForSchedule) { * @return * @throws ParseException */ - public static Date parseDate(String date) throws ParseException{ + public static DateTime parseDate(String date) throws ParseException{ try{ - return yyyyMMdd.parse(date); + return new DateTime(yyyyMMdd.parse(date).getTime()); } catch(ParseException e){} try { - return yyyyMMddHHmmss.parse(date); + return new DateTime(yyyyMMddHHmmss.parse(date).getTime()); } catch (ParseException e) {} - return yyyyMMddTHHmmssSSSZ.parse(date); + try { + return new DateTime(yyyyMMddTHHmmssSSSZ.parse(date).getTime()); + } catch (ParseException e) {} + + return DateTime.parse(date); } public static LocalDate tryParse(String value, LocalDate defaultValue) { @@ -71,7 +74,7 @@ public static Date getDateFromString(String dateString) try { if(dateString!=null && !dateString.equals("null") && dateString.length()>0) { - parsed = sdf.parse(dateString.trim()); + parsed = yyyyMMddTHHmmssSSSZ.parse(dateString.trim()); } } catch (ParseException e) { e.printStackTrace(); diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/HttpResponse.java b/opensrp-common/src/main/java/org/opensrp/common/util/HttpResponse.java index 8d21745cac..8ead48f02b 100644 --- a/opensrp-common/src/main/java/org/opensrp/common/util/HttpResponse.java +++ b/opensrp-common/src/main/java/org/opensrp/common/util/HttpResponse.java @@ -3,11 +3,18 @@ public class HttpResponse { private final boolean isSuccess; private final String body; + private Integer statusCode; - public HttpResponse(boolean isSuccess, String body) { + public HttpResponse(boolean isSuccess, String body) { this.isSuccess = isSuccess; this.body = body; } + + public HttpResponse(boolean isSuccess, int statusCode, String body) { + this.isSuccess = isSuccess; + this.body = body; + this.statusCode = statusCode; + } public boolean isSuccess() { return isSuccess; @@ -16,4 +23,8 @@ public boolean isSuccess() { public String body() { return body; } + + public Integer statusCode() { + return statusCode; + } } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/HttpUtil.java b/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java similarity index 68% rename from opensrp-connector/src/main/java/org/opensrp/connector/HttpUtil.java rename to opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java index 59cc18d07a..a0d740bc90 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/HttpUtil.java +++ b/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java @@ -1,4 +1,4 @@ -package org.opensrp.connector; +package org.opensrp.common.util; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyStore; @@ -6,6 +6,7 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; @@ -20,18 +21,17 @@ import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; -import org.opensrp.common.util.HttpResponse; import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.mysql.jdbc.StringUtils; @Component public class HttpUtil { + public enum AuthType{ + BASIC, TOKEN, NONE + } + private final static DefaultHttpClient httpClient = init(); - @SuppressWarnings("deprecation") public static DefaultHttpClient init() { try { //TODO add option to ignore cetificate validation in opensrp.prop @@ -57,19 +57,28 @@ public static DefaultHttpClient init() { } public static HttpResponse post(String url, String payload, String data, String username,String password) { - return post(url, payload, data, username, password, "application/json"); + return post(url, payload, data, "application/json", AuthType.BASIC, username+":"+password); + } + + public static HttpResponse post(String url, String payload, String data) { + return post(url, payload, data, "application/json", AuthType.NONE, ""); + } + + public static HttpResponse postWithToken(String url, String payload, String data, String token) { + return post(url, payload, data, "application/json", AuthType.TOKEN, token); } - public static HttpResponse post(String url, String payload, String data, String username,String password, String contentType) { + public static HttpResponse post(String url, String payload, String data, String contentType, AuthType authType, String authString) { try { - HttpPost request = (HttpPost) makeConnection(url, payload, RequestMethod.POST, true, username, password); + HttpPost request = (HttpPost) makeConnection(url, payload, RequestMethod.POST, authType, authString); request.setHeader(HTTP.CONTENT_TYPE, contentType); - StringEntity entity = new StringEntity(data); + StringEntity entity = new StringEntity(data==null?"":data); System.out.println(data); entity.setContentEncoding(contentType); request.setEntity(entity); org.apache.http.HttpResponse response = httpClient.execute(request); - return new HttpResponse(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK, IOUtils.toString(response.getEntity().getContent())); + return new HttpResponse(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK, response.getStatusLine() + .getStatusCode(),IOUtils.toString(response.getEntity().getContent())); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); @@ -77,22 +86,34 @@ public static HttpResponse post(String url, String payload, String data, String } public static HttpResponse get(String url, String payload, String username, String password) { + return get(url, payload, AuthType.BASIC, username+":"+password); + } + + public static HttpResponse get(String url, String payload) { + return get(url, payload, AuthType.NONE, ""); + } + + public static HttpResponse getWithToken(String url, String payload, String token) { + return get(url, payload, AuthType.BASIC, token); + } + + public static HttpResponse get(String url, String payload, AuthType authType, String authString) { try { - HttpGet request = (HttpGet) makeConnection(url, payload, RequestMethod.GET, true, username, password); + HttpGet request = (HttpGet) makeConnection(url, payload, RequestMethod.GET, authType, authString); org.apache.http.HttpResponse response = httpClient.execute(request); - return new HttpResponse(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK, IOUtils.toString(response.getEntity().getContent())); + return new HttpResponse(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK, response.getStatusLine().getStatusCode(), IOUtils.toString(response.getEntity().getContent())); } catch (Exception e) { throw new RuntimeException(e); } } - static HttpRequestBase makeConnection(String url, String payload, RequestMethod method, boolean useBasicAuth, String username, String password) throws URISyntaxException { + static HttpRequestBase makeConnection(String url, String payload, RequestMethod method, AuthType authType, String authString) throws URISyntaxException { String charset = "UTF-8"; if(url.endsWith("/")){ url = url.substring(0, url.lastIndexOf("/")); } - url = (url+(StringUtils.isEmptyOrWhitespaceOnly(payload)?"":("?"+payload))).replaceAll(" ", "%20"); + url = (url+(StringUtils.isBlank(payload)?"":("?"+payload))).replaceAll(" ", "%20"); URI urlo = new URI(url); HttpRequestBase requestBase = null; @@ -108,10 +129,14 @@ else if(method.equals(RequestMethod.PUT)){ requestBase.setURI(urlo); requestBase.addHeader("Accept-Charset", charset); - if(useBasicAuth){ - String encoded = new String(Base64.encodeBase64((username+":"+password).getBytes())); + if(authType.name().equalsIgnoreCase("basic")){ + String encoded = authString.matches(".+:.+")?new String(Base64.encodeBase64(authString.getBytes())):authString; requestBase.addHeader("Authorization", "Basic "+encoded); } + else if(authType.name().equalsIgnoreCase("token")){ + requestBase.addHeader("Authorization", "Token "+authString); + } + System.out.println(url); return requestBase; } diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/RequestMethod.java b/opensrp-common/src/main/java/org/opensrp/common/util/RequestMethod.java new file mode 100644 index 0000000000..75bd743684 --- /dev/null +++ b/opensrp-common/src/main/java/org/opensrp/common/util/RequestMethod.java @@ -0,0 +1,5 @@ +package org.opensrp.common.util; + +public enum RequestMethod { + POST , GET, PUT +} diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/SecureSocketFactory.java b/opensrp-common/src/main/java/org/opensrp/common/util/SecureSocketFactory.java similarity index 95% rename from opensrp-connector/src/main/java/org/opensrp/connector/SecureSocketFactory.java rename to opensrp-common/src/main/java/org/opensrp/common/util/SecureSocketFactory.java index 6d23292df1..6e092246e9 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/SecureSocketFactory.java +++ b/opensrp-common/src/main/java/org/opensrp/common/util/SecureSocketFactory.java @@ -1,4 +1,4 @@ -package org.opensrp.connector; +package org.opensrp.common.util; import java.io.IOException; import java.net.InetAddress; diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/EncounterAtomfeed.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/EncounterAtomfeed.java index 1a9bb61867..9772ad81cc 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/EncounterAtomfeed.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/EncounterAtomfeed.java @@ -67,16 +67,16 @@ public T executeWithTransaction(AFTransactionWork action) throws RuntimeE public void process(Event event) { log.info("Processing item : "+event.getContent()); try { - String uuid = event.getContent().substring(event.getContent().lastIndexOf("/")+1); - JSONObject e = encounterService.getEncounterByUuid(uuid, true); + String content = event.getContent().substring(event.getContent().lastIndexOf("/")+1); + JSONObject e = encounterService.getEncounterByUuid(content, true); if(e == null){ - throw new RuntimeException("Encounter uuid ("+uuid+") specified in atomfeed content did not return any encounter."); + throw new RuntimeException("Encounter uuid specified in atomfeed content ("+content+") did not return any encounter."); } log.info(e.toString()); org.opensrp.domain.Event enc = encounterService.convertToEvent(e); - org.opensrp.domain.Event existing = eventService.find(uuid); + org.opensrp.domain.Event existing = eventService.find(e.getString("uuid")); if(existing == null){ log.info("New Event"); eventService.addEvent(enc); diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/PatientAtomfeed.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/PatientAtomfeed.java index 5d6fd1da47..c27ca1a7e5 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/PatientAtomfeed.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/PatientAtomfeed.java @@ -36,7 +36,6 @@ public class PatientAtomfeed extends OpenmrsService implements EventWorker, Atom private AtomFeedProperties atomFeedProperties; private AFTransactionManager transactionManager; - private WebClient webClient; private AtomFeedClient client; private PatientService patientService; @@ -56,7 +55,7 @@ public T executeWithTransaction(AFTransactionWork action) throws RuntimeE return action.execute(); } }; - this.webClient = new WebClient(); + WebClient webClient = new WebClient(); URI uri = new URI(OPENMRS_BASE_URL+OpenmrsConstants.ATOMFEED_URL+CATEGORY_URL); this.client = new AtomFeedClient(new AllFeeds(webClient), allMarkers, allFailedEvents, atomFeedProperties, transactionManager, uri, this); @@ -69,10 +68,10 @@ public T executeWithTransaction(AFTransactionWork action) throws RuntimeE public void process(Event event) { log.info("Processing item : "+event.getContent()); try { - String uuid = event.getContent().substring(event.getContent().lastIndexOf("/")+1); - JSONObject p = patientService.getPatientByUuid(uuid, true); + String content = event.getContent().substring(event.getContent().lastIndexOf("/")+1); + JSONObject p = patientService.getPatientByUuid(content, true); if(p == null){ - throw new RuntimeException("Patient uuid ("+uuid+") specified in atomfeed content did not return any patient."); + throw new RuntimeException("Patient uuid specified in atomfeed content ("+content+") did not return any patient."); } Client c = patientService.convertToClient(p); Client existing = clientService.findClient(c); @@ -84,12 +83,12 @@ public void process(Event event) { log.info("New Client -> Posted Thrive ID back to OpenMRS : "+newId); } else { - String srpIdInOpenmrs = c.getIdentifierMatchingRegex(PatientService.OPENSRP_IDENTIFIER_TYPE_MATCHER); - c = clientService.mergeClient(c); + String srpIdInOpenmrs = c.getBaseEntityId(); + Client cmerged = clientService.mergeClient(c); //TODO what if in any case thrive id is assigned to some other patient - if(StringUtils.isBlank(srpIdInOpenmrs) || !srpIdInOpenmrs.equalsIgnoreCase(c.getBaseEntityId())){ + if(StringUtils.isBlank(srpIdInOpenmrs) || !srpIdInOpenmrs.equalsIgnoreCase(cmerged.getBaseEntityId())){ // if openmrs doesnot have openSRP UID or have a different UID then update - JSONObject newId = patientService.addThriveId(c.getBaseEntityId(), p); + JSONObject newId = patientService.addThriveId(cmerged.getBaseEntityId(), p); log.info("Existing Client missing Valid SRP UID -> Posted Thrive ID back to OpenMRS : "+newId); } } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java index 1dcb88b45e..27561fe9b2 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java @@ -1,8 +1,6 @@ package org.opensrp.connector.openmrs.constants; -import org.ict4h.atomfeed.client.AtomFeedProperties; - /** * Mappings in OpenSRP for OpenMRS entities and properties */ @@ -11,16 +9,20 @@ public class OpenmrsConstants { public static final String SCHEDULER_TRACKER_SYNCER_SUBJECT = "OpenMRS Scheduler Tracker Syncer"; public static final String SCHEDULER_OPENMRS_ATOMFEED_SYNCER_SUBJECT = "OpenMRS Atomfeed Syncer"; public static final String ENROLLMENT_TRACK_UUID = "openmrsTrackUuid"; + public static final String SCHEDULER_OPENMRS_DATA_PUSH_SUBJECT = "OpenMRS Data Pusher"; public static final String ATOMFEED_URL = "ws/atomfeed"; public static final String ATOMFEED_DATABASE_CONNECTOR = "atomfeedDatabaseConnector"; - public enum ScheduleTrackerConfig { - openmrs_syncer_sync_by_last_update_enrollment, + public enum SchedulerConfig { + openmrs_syncer_sync_schedule_tracker_by_last_update_enrollment, + + openmrs_syncer_sync_client_by_date_updated, + openmrs_syncer_sync_client_by_date_voided, + openmrs_syncer_sync_event_by_date_updated, + openmrs_syncer_sync_event_by_date_voided, openmrs_syncer_sync_status, openmrs_syncer_sync_timestamp } - - public static AtomFeedProperties DEFUALT_ATOM_FEED_PROPERTIES = new AtomFeedProperties(); } \ No newline at end of file diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java index 65f2f29019..c823a421c4 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java @@ -1,25 +1,22 @@ package org.opensrp.connector.openmrs.schedule; -import java.text.ParseException; import java.util.List; -import java.util.Map; +import java.util.Map.Entry; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.joda.time.DateTime; -import org.json.JSONException; import org.json.JSONObject; import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.scheduletracking.api.domain.Enrollment; import org.motechproject.server.event.annotations.MotechListener; import org.opensrp.connector.openmrs.constants.OpenmrsConstants; -import org.opensrp.connector.openmrs.constants.OpenmrsConstants.ScheduleTrackerConfig; -import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold; +import org.opensrp.connector.openmrs.constants.OpenmrsConstants.SchedulerConfig; import org.opensrp.connector.openmrs.service.EncounterService; import org.opensrp.connector.openmrs.service.OpenmrsSchedulerService; import org.opensrp.connector.openmrs.service.PatientService; import org.opensrp.domain.AppStateToken; import org.opensrp.domain.Client; import org.opensrp.domain.Event; -import org.opensrp.form.domain.FormSubmission; import org.opensrp.scheduler.service.ActionService; import org.opensrp.scheduler.service.ScheduleService; import org.opensrp.service.ClientService; @@ -58,15 +55,27 @@ public OpenmrsSyncerListener(OpenmrsSchedulerService openmrsSchedulerService, this.eventService = eventService; this.clientService = clientService; - this.config.registerAppStateToken(ScheduleTrackerConfig.openmrs_syncer_sync_by_last_update_enrollment, - 0, "ScheduleTracker token to keep track of enrollment synced with OpenMRS", true); + this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_schedule_tracker_by_last_update_enrollment, + 0, "ScheduleTracker token to keep track of enrollment synced with OpenMRS", true); + + this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_client_by_date_updated, + 0, "OpenMRS data pusher token to keep track of new / updated clients synced with OpenMRS", true); + + this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_client_by_date_voided, + 0, "OpenMRS data pusher token to keep track of voided clients synced with OpenMRS", true); + + this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_event_by_date_updated, + 0, "OpenMRS data pusher token to keep track of new / updated events synced with OpenMRS", true); + + this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_event_by_date_voided, + 0, "OpenMRS data pusher token to keep track of voided events synced with OpenMRS", true); } @MotechListener(subjects = OpenmrsConstants.SCHEDULER_TRACKER_SYNCER_SUBJECT) public void scheduletrackerSyncer(MotechEvent event) { try{ - System.out.println("RUNNING SCHEDULER_TRACKER_SYNCER_SUBJECT"); - AppStateToken lastsync = config.getAppStateTokenByName(ScheduleTrackerConfig.openmrs_syncer_sync_by_last_update_enrollment); + System.out.println("RUNNING "+event.getSubject()); + AppStateToken lastsync = config.getAppStateTokenByName(SchedulerConfig.openmrs_syncer_sync_schedule_tracker_by_last_update_enrollment); DateTime start = lastsync==null||lastsync.getValue()==null?new DateTime().minusYears(33):new DateTime(lastsync.stringValue()); DateTime end = new DateTime(); List el = opensrpScheduleService.findEnrollmentByLastUpDate(start, end); @@ -89,46 +98,83 @@ public void scheduletrackerSyncer(MotechEvent event) { errorTraceService.log("ScheduleTracker Syncer Inactive Schedule", Enrollment.class.getName(), e.getId(), e1.getStackTrace().toString(), ""); } } - config.updateAppStateToken(ScheduleTrackerConfig.openmrs_syncer_sync_by_last_update_enrollment, end); + config.updateAppStateToken(SchedulerConfig.openmrs_syncer_sync_schedule_tracker_by_last_update_enrollment, end); } catch(Exception e){ e.printStackTrace(); } } - @SuppressWarnings("unchecked") - @MotechListener(subjects = "PUSH FORM SUBMISSION TO OPENMRS")//TODO constant - public void pushFormSubmissionToOpenMRS(MotechEvent event) { + @MotechListener(subjects = OpenmrsConstants.SCHEDULER_OPENMRS_DATA_PUSH_SUBJECT) + public void pushToOpenMRS(MotechEvent event) { try{ - System.out.println("RUNNING PUSH FORM SUBMISSION TO OPENMRS"); - Map d = (Map)event.getParameters().get("data"); - Client c = (Client)d.get("client"); - Event e = (Event)d.get("event"); - Map> dep = (Map>) d.get("dependents"); - - e.addDetails("OPENMRS_UUID", addEventToOpenMRS(c, e)); + System.out.println("RUNNING "+event.getSubject()); - eventService.updateEvent(e); + AppStateToken lastsync = config.getAppStateTokenByName(SchedulerConfig.openmrs_syncer_sync_client_by_date_updated); + DateTime start = lastsync==null||lastsync.getValue()==null?new DateTime().minusYears(33):new DateTime(lastsync.stringValue()); + DateTime end = new DateTime(); + + System.out.println("START "+start+" , END "+end); + + List cl = clientService.findByCriteria(null, null, null, null, null, null, null, null, start, end); + System.out.println("Clients list size "+cl.size()); + for (Client c : cl) { + try{ + String uuid = c.getIdentifier(PatientService.OPENMRS_UUID_IDENTIFIER_TYPE); + + if(uuid == null){ + JSONObject p = patientService.getPatientByIdentifier(c.getBaseEntityId()); + for (Entry id : c.getIdentifiers().entrySet()) { + p = patientService.getPatientByIdentifier(id.getValue()); + if(p != null){ + break; + } + } + if(p != null){ + uuid = p.getString("uuid"); + } + } + if(uuid != null){ + System.out.println("Updating patient "+uuid); + patientService.updatePatient(c, uuid); + } + else { + System.out.println(patientService.createPatient(c)); + } + } + catch(Exception ex1){ + ex1.printStackTrace(); + errorTraceService.log("OPENMRS FAILED CLIENT PUSH", Client.class.getName(), c.getBaseEntityId(), ExceptionUtils.getStackTrace(ex1), ""); + } + } + config.updateAppStateToken(SchedulerConfig.openmrs_syncer_sync_client_by_date_updated, end); + + System.out.println("RUNNING FOR EVENTS"); - for (String k : dep.keySet()) { - addEventToOpenMRS((Client)dep.get(k).get("client"), (Event)dep.get(k).get("event")); + lastsync = config.getAppStateTokenByName(SchedulerConfig.openmrs_syncer_sync_event_by_date_updated); + start = lastsync==null||lastsync.getValue()==null?new DateTime().minusYears(33):new DateTime(lastsync.stringValue()); + end = new DateTime(); + + List el = eventService.findEventsBy(null, null, null, null, null, null, null, start, end); + for (Event e : el) { + try{ + String uuid = e.getIdentifier(EncounterService.OPENMRS_UUID_IDENTIFIER_TYPE); + if(uuid != null){ + encounterService.updateEncounter(e); + } + else { + System.out.println(encounterService.createEncounter(e)); + } + } + catch(Exception ex2){ + ex2.printStackTrace(); + errorTraceService.log("OPENMRS FAILED EVENT PUSH", Event.class.getName(), e.getId(), ExceptionUtils.getStackTrace(ex2), ""); + } } + config.updateAppStateToken(SchedulerConfig.openmrs_syncer_sync_event_by_date_updated, end); } - catch(Exception e){ - e.printStackTrace(); + catch(Exception ex){ + ex.printStackTrace(); } } - - private String addEventToOpenMRS(Client c, Event e) throws ParseException, IllegalStateException, JSONException{ -// if(formEntityConverter.isOpenmrsForm(formSubmission)){ - JSONObject p = patientService.getPatientByIdentifier(c.getBaseEntityId());//TODO by all identifiers - if(p == null){ - System.out.println(patientService.createPatient(c)); - } - - JSONObject ej = encounterService.createEncounter(e); - return ej.getString("uuid"); - //} - } - } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java index 0ba3ff705e..54c3b8de53 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java @@ -11,7 +11,7 @@ import org.json.JSONException; import org.json.JSONObject; import org.opensrp.common.util.HttpResponse; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.opensrp.domain.Client; import org.opensrp.domain.Event; import org.opensrp.domain.Obs; @@ -269,7 +269,7 @@ public Event convertToEvent(JSONObject encounter) throws JSONException{ JSONObject creator = encounter.getJSONObject("auditInfo").getJSONObject("creator"); e.withBaseEntityId(c.getBaseEntityId()) .withCreator(new User(creator.getString("uuid"), creator.getString("display"), null, null)) - .withDateCreated(new Date()); + .withDateCreated(DateTime.now()); e.withEventDate(new DateTime(encounter.getString("encounterDatetime"))) //.withEntityType(entityType) //TODO diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java index 5fcb3baec0..f18a8b83eb 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java @@ -3,7 +3,7 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold; import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold.HouseholdMember; import org.springframework.beans.factory.annotation.Autowired; diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsLocationService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsLocationService.java index a303151482..438f462c48 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsLocationService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsLocationService.java @@ -6,7 +6,7 @@ import org.opensrp.api.domain.Location; import org.opensrp.api.util.LocationTree; import org.opensrp.common.util.HttpResponse; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.springframework.stereotype.Service; import com.mysql.jdbc.StringUtils; diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsReportingService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsReportingService.java index d90a6d1eab..17f58b2fb3 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsReportingService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsReportingService.java @@ -6,7 +6,7 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.springframework.stereotype.Service; @Service diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsSchedulerService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsSchedulerService.java index d738ff3dc4..b083f065fe 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsSchedulerService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsSchedulerService.java @@ -13,7 +13,7 @@ import org.motechproject.scheduletracking.api.domain.Enrollment; import org.motechproject.scheduletracking.api.domain.MilestoneFulfillment; import org.motechproject.scheduletracking.api.domain.json.ScheduleRecord; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.opensrp.connector.openmrs.constants.OpenmrsConstants; import org.opensrp.scheduler.Action; import org.opensrp.scheduler.service.AllScheduleWrapper; diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsService.java index f56d886991..797816d3ff 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsService.java @@ -3,7 +3,7 @@ import java.text.SimpleDateFormat; import java.util.Date; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsUserService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsUserService.java index 29bff20bbf..54fa20bd75 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsUserService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsUserService.java @@ -5,7 +5,7 @@ import org.json.JSONObject; import org.opensrp.api.domain.User; import org.opensrp.common.util.HttpResponse; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.springframework.stereotype.Service; @Service diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/PatientService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/PatientService.java index 0b6b65b779..191f7c2dd8 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/PatientService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/PatientService.java @@ -11,7 +11,8 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.DateUtil; +import org.opensrp.common.util.HttpUtil; import org.opensrp.domain.Address; import org.opensrp.domain.Client; import org.springframework.stereotype.Service; @@ -170,10 +171,10 @@ public JSONArray convertAddressesToOpenmrsJson(List
adl) throws JSONExc jao.put("latitude", ad.getLatitude()); jao.put("longitude", ad.getLongitude()); if(ad.getStartDate() != null){ - jao.put("startDate", OPENMRS_DATE.format(ad.getStartDate())); + jao.put("startDate", OPENMRS_DATE.format(ad.getStartDate().toDate())); } if(ad.getEndDate() != null){ - jao.put("endDate", OPENMRS_DATE.format(ad.getEndDate())); + jao.put("endDate", OPENMRS_DATE.format(ad.getEndDate().toDate())); } jaar.put(jao); @@ -220,6 +221,44 @@ public JSONObject createPatient(Client c) throws JSONException return new JSONObject(HttpUtil.post(getURL()+"/"+PATIENT_URL, "", p.toString(), OPENMRS_USER, OPENMRS_PWD).body()); } + public JSONObject updatePatient(Client c, String uuid) throws JSONException + { + JSONObject p = new JSONObject(); + p.put("person", convertBaseEntityToOpenmrsJson(c)); + JSONArray ids = new JSONArray(); + if(c.getIdentifiers() != null){ + for (Entry id : c.getIdentifiers().entrySet()) { + JSONObject jio = new JSONObject(); + JSONObject idobj = getIdentifierType(id.getKey()); + if(idobj == null){ + idobj = createIdentifierType(id.getKey(), id.getKey()+" - FOR THRIVE OPENSRP"); + } + jio.put("identifierType", idobj.getString("uuid")); + jio.put("identifier", id.getValue()); + Object cloc = c.getAttribute("Location"); + jio.put("location", cloc == null?"Unknown Location":cloc); + //jio.put("preferred", true); + + ids.put(jio); + }} + + JSONObject jio = new JSONObject(); + JSONObject ido = getIdentifierType(OPENSRP_IDENTIFIER_TYPE); + if(ido == null){ + ido = createIdentifierType(OPENSRP_IDENTIFIER_TYPE, OPENSRP_IDENTIFIER_TYPE+" - FOR THRIVE OPENSRP"); + } + jio.put("identifierType", ido.getString("uuid")); + jio.put("identifier", c.getBaseEntityId()); + Object cloc = c.getAttribute("Location"); + jio.put("location", cloc == null?"Unknown Location":cloc); + jio.put("preferred", true); + + ids.put(jio); + + p.put("identifiers", ids); + return new JSONObject(HttpUtil.post(getURL()+"/"+PATIENT_URL+"/"+uuid, "", p.toString(), OPENMRS_USER, OPENMRS_PWD).body()); + } + public JSONObject addThriveId(String baseEntityId, JSONObject patient) throws JSONException { JSONObject jio = new JSONObject(); @@ -276,8 +315,8 @@ public Client convertToClient(JSONObject patient) throws JSONException { if(pr.has("addresses")){ for (int i = 0; i < pr.getJSONArray("addresses").length(); i++) { JSONObject ad = pr.getJSONArray("addresses").getJSONObject(i); - Date startDate = ad.has("startDate")&&!ad.getString("startDate").equalsIgnoreCase("null")?new DateTime(ad.getString("startDate")).toDate():null; - Date endDate = ad.has("startDate")&&!ad.getString("endDate").equalsIgnoreCase("null")?new DateTime(ad.getString("endDate")).toDate():null;; + DateTime startDate = ad.has("startDate")&&!ad.getString("startDate").equalsIgnoreCase("null")?new DateTime(ad.getString("startDate")):null; + DateTime endDate = ad.has("startDate")&&!ad.getString("endDate").equalsIgnoreCase("null")?new DateTime(ad.getString("endDate")):null;; Address a = new Address(ad.getString("address6"), startDate, endDate, null, ad.getString("latitude"), ad.getString("longitude"), ad.getString("postalCode"), ad.getString("stateProvince"), ad.getString("country")); diff --git a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/OpenmrsUserServiceTest.java b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/OpenmrsUserServiceTest.java index 6950ab5194..26984d5718 100644 --- a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/OpenmrsUserServiceTest.java +++ b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/OpenmrsUserServiceTest.java @@ -12,7 +12,7 @@ import static org.mockito.Mockito.*; import org.opensrp.common.util.HttpResponse; -import org.opensrp.connector.HttpUtil; +import org.opensrp.common.util.HttpUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; diff --git a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/PatientTest.java b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/PatientTest.java index 0d02cdcce4..ece6ef87bd 100644 --- a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/PatientTest.java +++ b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/PatientTest.java @@ -24,14 +24,18 @@ public PatientTest() throws IOException { @Before public void setup(){ + pushToOpenmrsForTest = true; + openmrsUsername = "admin"; + openmrsPassword = "0p3n5rpAdmin"; + openmrsOpenmrsUrl = "http://46.101.51.199:8080/openmrs"; s = new PatientService(openmrsOpenmrsUrl, openmrsUsername, openmrsPassword); } @Test public void shouldCreatePerson() throws JSONException { List
addresses = new ArrayList<>(); - addresses.add(new Address("BIRTH", new Date(), new Date(), null, "LAT", "LON", "PCODE", "SINDH", "PK")); - addresses.add(new Address("DEATH", new Date(), new Date(), null, "LATd", "LONd", "dPCODE", "KPK", "PK")); + addresses.add(new Address("BIRTH", DateTime.now(), DateTime.now(), null, "LAT", "LON", "PCODE", "SINDH", "PK")); + addresses.add(new Address("DEATH", DateTime.now(), DateTime.now(), null, "LATd", "LONd", "dPCODE", "KPK", "PK")); Map attribs = new HashMap<>(); //attribs.put("Household ID", "HH112"); Client c = new Client(UUID.randomUUID().toString()) diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Address.java b/opensrp-core/src/main/java/org/opensrp/domain/Address.java index ae6c8fb99f..c090fca045 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/Address.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/Address.java @@ -1,6 +1,5 @@ package org.opensrp.domain; -import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -8,6 +7,7 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonProperty; +import org.joda.time.DateTime; import org.opensrp.common.AddressField; public class Address{ @@ -17,9 +17,9 @@ public class Address{ @JsonProperty private String addressType; @JsonProperty - private Date startDate; + private DateTime startDate; @JsonProperty - private Date endDate; + private DateTime endDate; @JsonProperty private Map addressFields; @JsonProperty @@ -48,7 +48,7 @@ public class Address{ public Address() { } - public Address(String addressType, Date startDate, Date endDate, Map addressFields, + public Address(String addressType, DateTime startDate, DateTime endDate, Map addressFields, String latitude, String longitude, String postalCode, String stateProvince, String country) { this.addressType = addressType; this.startDate = startDate; @@ -69,19 +69,19 @@ public void setAddressType(String addressType) { this.addressType = addressType; } - public Date getStartDate() { + public DateTime getStartDate() { return startDate; } - public void setStartDate(Date startDate) { + public void setStartDate(DateTime startDate) { this.startDate = startDate; } - public Date getEndDate() { + public DateTime getEndDate() { return endDate; } - public void setEndDate(Date endDate) { + public void setEndDate(DateTime endDate) { this.endDate = endDate; } @@ -244,7 +244,7 @@ public void setCountry(String country) { */ @JsonIgnore public boolean isActive() { - return endDate==null||endDate.after(new Date()); + return endDate==null||endDate.isAfter(DateTime.now()); } /** @@ -256,10 +256,10 @@ private long durationInMillis() { return -1; } if(endDate == null){ - return new Date().getTime()-startDate.getTime(); + return DateTime.now().getMillis()-startDate.getMillis(); } - return endDate.getTime()-startDate.getTime(); + return endDate.getMillis()-startDate.getMillis(); } /** @@ -306,7 +306,7 @@ public Address withAddressType(String addressType) { * @param endDate * @return */ - public Address withStartDate(Date startDate) { + public Address withStartDate(DateTime startDate) { this.startDate = startDate; return this; } @@ -316,7 +316,7 @@ public Address withStartDate(Date startDate) { * @param endDate * @return */ - public Address withEndDate(Date endDate) { + public Address withEndDate(DateTime endDate) { this.endDate = endDate; return this; } diff --git a/opensrp-core/src/main/java/org/opensrp/domain/BaseDataObject.java b/opensrp-core/src/main/java/org/opensrp/domain/BaseDataObject.java index 40ff526862..f7c5e56edc 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/BaseDataObject.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/BaseDataObject.java @@ -4,6 +4,7 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.codehaus.jackson.annotate.JsonProperty; +import org.joda.time.DateTime; import org.motechproject.model.MotechBaseDataObject; public abstract class BaseDataObject extends MotechBaseDataObject { @@ -11,15 +12,15 @@ public abstract class BaseDataObject extends MotechBaseDataObject { @JsonProperty private User creator; @JsonProperty - private Date dateCreated; + private DateTime dateCreated; @JsonProperty private User editor; @JsonProperty - private Date dateEdited; + private DateTime dateEdited; @JsonProperty private Boolean voided; @JsonProperty - private Date dateVoided; + private DateTime dateVoided; @JsonProperty private User voider; @JsonProperty @@ -35,11 +36,11 @@ public void setCreator(User creator) { this.creator = creator; } - public Date getDateCreated() { + public DateTime getDateCreated() { return dateCreated; } - public void setDateCreated(Date dateCreated) { + public void setDateCreated(DateTime dateCreated) { this.dateCreated = dateCreated; } @@ -51,11 +52,11 @@ public void setEditor(User editor) { this.editor = editor; } - public Date getDateEdited() { + public DateTime getDateEdited() { return dateEdited; } - public void setDateEdited(Date dateEdited) { + public void setDateEdited(DateTime dateEdited) { this.dateEdited = dateEdited; } @@ -67,11 +68,11 @@ public void setVoided(Boolean voided) { this.voided = voided; } - public Date getDateVoided() { + public DateTime getDateVoided() { return dateVoided; } - public void setDateVoided(Date dateVoided) { + public void setDateVoided(DateTime dateVoided) { this.dateVoided = dateVoided; } @@ -96,7 +97,7 @@ public BaseDataObject withCreator(User creator) { return this; } - public BaseDataObject withDateCreated(Date dateCreated) { + public BaseDataObject withDateCreated(DateTime dateCreated) { this.dateCreated = dateCreated; return this; } @@ -106,7 +107,7 @@ public BaseDataObject withEditor(User editor) { return this; } - public BaseDataObject withDateEdited(Date dateEdited) { + public BaseDataObject withDateEdited(DateTime dateEdited) { this.dateEdited = dateEdited; return this; } @@ -116,7 +117,7 @@ public BaseDataObject withVoided(Boolean voided) { return this; } - public BaseDataObject withDateVoided(Date dateVoided) { + public BaseDataObject withDateVoided(DateTime dateVoided) { this.dateVoided = dateVoided; return this; } diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Client.java b/opensrp-core/src/main/java/org/opensrp/domain/Client.java index cab34e91ea..84f589bca4 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/Client.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/Client.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -112,6 +113,20 @@ public void setLastName(String lastName) { this.lastName = lastName; } + public String fullName() { + String n = ""; + if(StringUtils.isNotBlank(firstName)){ + n += firstName; + } + if(StringUtils.isNotBlank(middleName)){ + n += " "+ middleName; + } + if(StringUtils.isNotBlank(lastName)){ + n += " " + lastName; + } + return n.trim(); + } + public DateTime getBirthdate() { return birthdate; } diff --git a/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java b/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java index 1af44454ca..8fd911dc9c 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java @@ -4,6 +4,7 @@ import org.codehaus.jackson.annotate.JsonProperty; import org.ektorp.support.TypeDiscriminator; +import org.joda.time.DateTime; import org.motechproject.model.MotechBaseDataObject; /** @@ -16,7 +17,7 @@ public class ErrorTrace extends MotechBaseDataObject { * @JsonProperty private String id; */ @JsonProperty - private Date dateOccurred; + private DateTime dateOccurred; @JsonProperty private String errorType; @JsonProperty @@ -47,7 +48,7 @@ public ErrorTrace() { * * */ - public ErrorTrace(Date dateOccurred, String errorType, String occuredAt, + public ErrorTrace(DateTime dateOccurred, String errorType, String occuredAt, String stackTrace, String status, String documentType) { this.dateOccurred = dateOccurred; // this.id=id; @@ -59,7 +60,7 @@ public ErrorTrace(Date dateOccurred, String errorType, String occuredAt, } - public ErrorTrace(String recordId, Date date, String name, + public ErrorTrace(String recordId, DateTime date, String name, String occuredAt, String stackTrace, String status) { this.dateOccurred = date; this.recordId = recordId; @@ -70,11 +71,11 @@ public ErrorTrace(String recordId, Date date, String name, } - public Date getDateOccurred() { + public DateTime getDateOccurred() { return dateOccurred; } - public void setDateOccurred(Date dateOccurred) { + public void setDateOccurred(DateTime dateOccurred) { this.dateOccurred = dateOccurred; } @@ -121,11 +122,11 @@ public void setRecordId(String recordId) { } - public Date getDate() { + public DateTime getDate() { return dateOccurred; } - public void setDate(Date date) { + public void setDate(DateTime date) { this.dateOccurred = date; } diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Event.java b/opensrp-core/src/main/java/org/opensrp/domain/Event.java index 5e3f05d78e..85e1a79ed0 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/Event.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/Event.java @@ -10,10 +10,12 @@ import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import org.ektorp.support.TypeDiscriminator; import org.joda.time.DateTime; +@JsonIgnoreProperties(ignoreUnknown = true) @TypeDiscriminator("doc.type == 'Event'") public class Event extends BaseDataObject{ diff --git a/opensrp-core/src/main/java/org/opensrp/repository/lucene/Query.java b/opensrp-core/src/main/java/org/opensrp/repository/lucene/Query.java index 583f667bb5..02c86cbeb3 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/lucene/Query.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/lucene/Query.java @@ -30,11 +30,11 @@ public Query like(String name, String value) { return this; } public Query eq(String name, DateTime value){ - addToQuery(name+":["+value.toString("yyyy-MM-dd")+" TO "+value.toString("yyyy-MM-dd")+"] "); + addToQuery(name+":["+value.withTimeAtStartOfDay().toString("yyyy-MM-dd'T'HH:mm:ss")+" TO "+value.plusDays(1).withTimeAtStartOfDay().toString("yyyy-MM-dd'T'HH:mm:ss")+"] "); return this; } public Query between(String name, DateTime from, DateTime to){ - addToQuery(name+":["+from.toString("yyyy-MM-dd")+" TO "+to.toString("yyyy-MM-dd")+"] "); + addToQuery(name+":["+from.toString("yyyy-MM-dd'T'HH:mm:ss")+" TO "+to.toString("yyyy-MM-dd'T'HH:mm:ss")+"] "); return this; } private void addToQuery(String q){ diff --git a/opensrp-core/src/main/java/org/opensrp/service/ClientService.java b/opensrp-core/src/main/java/org/opensrp/service/ClientService.java index 6c3306bb8b..3a23c51e7b 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/ClientService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/ClientService.java @@ -66,10 +66,10 @@ public List findByCriteria(String nameLike, String gender, DateTime birt return allClients.findByCriteria(nameLike, gender, birthdateFrom, birthdateTo, deathdateFrom, deathdateTo, attributeType, attributeValue, null, null, null, null, null, null, null, null, lastEditFrom, lastEditTo); } - public List findByCriteria(String addressType, String country, String stateProvince, String cityVillage, String countyDistrict, +/* public List findByCriteria(String addressType, String country, String stateProvince, String cityVillage, String countyDistrict, String subDistrict, String town, String subTown, DateTime lastEditFrom, DateTime lastEditTo) { return allClients.findByCriteria(null, null, null, null, null, null, null, null, addressType, country, stateProvince, cityVillage, countyDistrict, subDistrict, town, subTown, lastEditFrom, lastEditTo); - } + }*/ public List findByDynamicQuery(String query) { return allClients.findByDynamicQuery(query); @@ -85,7 +85,7 @@ public Client addClient(Client client) throw new IllegalArgumentException("A client already exists with given list of identifiers. Consider updating data.["+c+"]"); } - client.setDateCreated(new Date()); + client.setDateCreated(DateTime.now()); allClients.add(client); return client; } @@ -141,7 +141,7 @@ public void updateClient(Client updatedClient) throws JSONException throw new IllegalArgumentException("No client found with given list of identifiers. Consider adding new!"); } - updatedClient.setDateEdited(new Date()); + updatedClient.setDateEdited(DateTime.now()); allClients.update(updatedClient); } @@ -188,7 +188,7 @@ public Client mergeClient(Client updatedClient) } } - original.setDateEdited(new Date()); + original.setDateEdited(DateTime.now()); allClients.update(original); return original; } diff --git a/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java b/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java index 6f9e65f794..9ddc1f6921 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java @@ -6,6 +6,7 @@ import java.util.List; import org.ektorp.DocumentNotFoundException; +import org.joda.time.DateTime; import org.opensrp.domain.ErrorTrace; import org.opensrp.repository.AllErrorTrace; import org.springframework.beans.factory.annotation.Autowired; @@ -48,7 +49,7 @@ public void log(String errorType , String documentType, String recordId ,String error.setRecordId(recordId); error.setStackTrace(stackTrace); error.setRetryUrl(retryURL); - error.setDateOccurred(new Date()); + error.setDateOccurred(DateTime.now()); addError(error); } diff --git a/opensrp-core/src/main/java/org/opensrp/service/EventService.java b/opensrp-core/src/main/java/org/opensrp/service/EventService.java index 826a52c250..efd8a37ea2 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/EventService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/EventService.java @@ -101,7 +101,7 @@ public synchronized Event addEvent(Event event) throw new IllegalArgumentException("An event already exists with given baseEntity and formSubmission combination. Consider updating"); } - event.setDateCreated(new Date()); + event.setDateCreated(DateTime.now()); allEvents.add(event); return event; } @@ -113,7 +113,7 @@ public void updateEvent(Event updatedEvent) throw new IllegalArgumentException("Event to be updated is not an existing and persisting domain object. Update database object instead of new pojo"); } - updatedEvent.setDateEdited(new Date()); + updatedEvent.setDateEdited(DateTime.now()); allEvents.update(updatedEvent); } @@ -161,7 +161,7 @@ public Event mergeEvent(Event updatedEvent) } } - original.setDateEdited(new Date()); + original.setDateEdited(DateTime.now()); allEvents.update(original); return original; } diff --git a/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormSubmissionListener.java b/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormSubmissionListener.java index 73d142bb5f..ec158eb84f 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormSubmissionListener.java +++ b/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormSubmissionListener.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.concurrent.locks.ReentrantLock; +import org.joda.time.DateTime; import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.server.event.annotations.MotechListener; import org.opensrp.common.AllConstants; @@ -87,7 +88,7 @@ public void parseForms(MotechEvent event) { } catch(Exception e){ e.printStackTrace(); - errorTraceService.addError(new ErrorTrace(new Date(), "FormSubmissionProcessor", this.getClass().getName(), e.getStackTrace().toString(), "unsolved", FormSubmission.class.getName())); + errorTraceService.addError(new ErrorTrace(DateTime.now(), "FormSubmissionProcessor", this.getClass().getName(), e.getStackTrace().toString(), "unsolved", FormSubmission.class.getName())); } } } catch (Exception e) { diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java index 6bc413c596..8ffff25d67 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java @@ -51,7 +51,7 @@ public void shouldFetchBaseEntityForClientData() throws Exception { .withLastName("C last n") .withMiddleName("C middle n") .withGender(Gender.FEMALE); - c.withAddress(new Address("birthplace", new Date(System.currentTimeMillis()-1000*60*60*24*2), new Date(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); + c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); c.withAttribute("ETHNICITY", "Mughal"); c.withIdentifier("Program ID", "01001221"); @@ -82,7 +82,7 @@ public void shouldFetchBaseEntityByIdentifier() throws Exception { .withLastName("C last n") .withMiddleName("C middle n") .withGender(Gender.MALE); - c.withAddress(new Address("birthplace", new Date(System.currentTimeMillis()-1000*60*60*24*2), new Date(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); + c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); c.withAttribute("ETHNICITY", "Mughal"); c.withIdentifier("Program ID", "01001222"); diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java index 8c541d76b7..fda9300154 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java @@ -108,6 +108,18 @@ public void shouldMergeSuccessfullyIfClientFound() throws JSONException {//TODO clientService.mergeClient(cu); } + @Test + public void shouldSearchByLastUpdatedDate() throws JSONException {//TODO + DateTime start = DateTime.now(); + + addClients(); + + DateTime end = DateTime.now(); + + List cll = clientService.findByCriteria(null, null, null, null, null, null, null, null, start, end); + assertEquals(10, cll.size()); + } + public static void main(String[] args) { System.out.println(new DateTime("2016-01-23").toString("MMMM (yyyy)")); } @@ -209,7 +221,7 @@ public void shouldFetchClientByIdentifier() .withLastName("C last n") .withMiddleName("C middle n") .withGender(Gender.MALE); - c.withAddress(new Address("birthplace", new Date(System.currentTimeMillis()-1000*60*60*24*2), new Date(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); + c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); c.withAttribute("ETHNICITY", "Mughal"); c.withIdentifier("Program ID", "01001222"); @@ -241,7 +253,7 @@ public void shouldFetchClientByAttribute() .withLastName("C last n") .withMiddleName("C middle n") .withGender(Gender.MALE); - c.withAddress(new Address("birthplace", new Date(System.currentTimeMillis()-1000*60*60*24*2), new Date(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); + c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); c.withAttribute("ETHNICITY", "Mughal"); c.withIdentifier("Program ID", "01001222"); diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java index 16d58a8060..75641379dc 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java @@ -4,6 +4,7 @@ import java.util.Date; +import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,7 +32,7 @@ public void shouldAddError()throws Exception //ErrorTrace error=new ErrorTrace(new Date(), "Error Testing" , "not availalbe","this is an Testing Error", "unsolved"); ErrorTrace error=new ErrorTrace(); error.setErrorType("error loggging test"); - error.setDate(new Date()); + error.setDate(DateTime.now()); error.setStackTrace("Complete Stack Trace :"); error.setStatus("unsolved"); error.setDocumentType("Test Document"); diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java index 4db259881d..267a9f0f94 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.Set; +import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,7 +39,7 @@ public void shouldAddLocation() throws Exception addressFields.put("Union","Gaya Bari"); addressFields.put("Ward","Middle Gaya Bari"); - Address address = new Address("Permanent", new Date(), new Date(), + Address address = new Address("Permanent", DateTime.now(), DateTime.now(), addressFields, "70.5", "40.5", "6300", "", "Bangladesh"); Map identifiers = new HashMap(); diff --git a/opensrp-core/src/test/java/org/opensrp/scheduler/router/ActionServiceTest.java b/opensrp-core/src/test/java/org/opensrp/scheduler/ActionServiceTest.java similarity index 88% rename from opensrp-core/src/test/java/org/opensrp/scheduler/router/ActionServiceTest.java rename to opensrp-core/src/test/java/org/opensrp/scheduler/ActionServiceTest.java index 449f7baef6..68f5d54123 100644 --- a/opensrp-core/src/test/java/org/opensrp/scheduler/router/ActionServiceTest.java +++ b/opensrp-core/src/test/java/org/opensrp/scheduler/ActionServiceTest.java @@ -1,4 +1,4 @@ -/*package org.opensrp.scheduler.router; +/*package org.opensrp.scheduler; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; @@ -23,6 +23,7 @@ import org.opensrp.dto.MonthSummaryDatum; import org.opensrp.scheduler.Action; import org.opensrp.scheduler.repository.AllActions; +import org.opensrp.scheduler.repository.AllAlerts; import org.opensrp.scheduler.service.ActionService; import org.opensrp.service.BaseEntityService; @@ -31,6 +32,10 @@ public class ActionServiceTest { @Mock private AllActions allActions; + + @Mock + private AllAlerts allAlerts; + @Mock private BaseEntityService baseEntityService; @@ -39,24 +44,25 @@ public class ActionServiceTest { @Before public void setUp() throws Exception { initMocks(this); - service = new ActionService(allActions, null); + allActions.removeAll(); + allAlerts.removeAll(); + service = new ActionService(allActions, allAlerts); } @Test - public void shouldSaveAlertActionForMother() throws Exception { - when(baseEntityService.findByBaseEntityId("Case X")).thenReturn(new BaseEntity("Case X")); - + public void shouldSaveAlertActionForEntity() throws Exception { DateTime dueDate = DateTime.now().minusDays(1); DateTime expiryDate = dueDate.plusWeeks(2); service.alertForBeneficiary("mother", "Case X", "ANM ID M", "Ante Natal Care - Normal", "ANC 1", normal, dueDate, expiryDate); - verify(allActions).addOrUpdateAlert(new Action("Case X", "ANM ID M", ActionData.createAlert("mother", "Ante Natal Care - Normal", "ANC 1", normal, dueDate, expiryDate))); + Action action = new Action("Case X", "ANM ID M", ActionData.createAlert("mother", "Ante Natal Care - Normal", "ANC 1", normal, dueDate, expiryDate)); + verify(allActions).addOrUpdateAlert(action); + verify(allActions).add(action); + verify(allAlerts).addOrUpdateScheduleNotificationAlert("mother", "Case X", "ANM ID M", "Ante Natal Care - Normal", "ANC 1", normal, dueDate, expiryDate); } @Test public void shouldDeleteExistingAlertBeforeCreatingNewOne() throws Exception { - when(allMothers.findByCaseId("Case X")).thenReturn(new Mother("Case X", "EC-CASE-1", "Thayi 1").withAnm("ANM ID M")); - DateTime dueDate = DateTime.now().minusDays(1); DateTime expiryDate = dueDate.plusWeeks(2); service.alertForBeneficiary(mother, "Case X", "ANM ID M", "Ante Natal Care - Normal", "ANC 1", normal, dueDate, expiryDate); diff --git a/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml b/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml index 8b298def0c..20976fab43 100644 --- a/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml +++ b/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml @@ -17,10 +17,8 @@ - - + diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/ActionController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/ActionController.java index c6e01578c4..b7b107a396 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/controller/ActionController.java +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/ActionController.java @@ -1,9 +1,31 @@ package org.opensrp.web.controller; -import ch.lambdaj.function.convert.Converter; +import static ch.lambdaj.collection.LambdaCollections.with; -import org.opensrp.scheduler.service.ActionService; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.opensrp.domain.Client; import org.opensrp.dto.Action; +import org.opensrp.repository.AllClients; +import org.opensrp.scheduler.Alert; +import org.opensrp.scheduler.repository.AllAlerts; +import org.opensrp.scheduler.service.ActionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -11,18 +33,19 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import java.util.ArrayList; -import java.util.List; - -import static ch.lambdaj.collection.LambdaCollections.with; +import ch.lambdaj.function.convert.Converter; @Controller public class ActionController { private ActionService actionService; + private AllClients allClients; + private AllAlerts allAlerts; @Autowired - public ActionController(ActionService actionService) { + public ActionController(ActionService actionService, AllClients c, AllAlerts allAlerts) { this.actionService = actionService; + this.allClients = c; + this.allAlerts = allAlerts; } @RequestMapping(method = RequestMethod.GET, value = "/actions") @@ -36,5 +59,81 @@ public Action convert(org.opensrp.scheduler.Action action) { } }); } + + @RequestMapping(method = RequestMethod.GET, value = "/alert_delete") + @ResponseBody + public void deleteDuplicateAlerts(@RequestParam("key") String key){ + if(!key.equalsIgnoreCase("20160727KiSafaiMuhim")){ + throw new RuntimeException("Invalid Key"); + } + for (Client c : allClients.findAllClients()) { + List al = allAlerts.findActiveAlertByEntityId(c.getBaseEntityId()); + Logger.getLogger(getClass()).warn(al.size()+" Alerts for "+c.getBaseEntityId()); + Map am = new HashMap<>(); + for (Alert a : al) { + if(am.containsKey(a.triggerName())){ + Logger.getLogger(getClass()).warn("Removing trigger "+a.triggerName()); + allAlerts.safeRemove(a); + } + else { + am.put(a.triggerName(), a); + } + } + } + } + + public static void main(String[] args) throws JSONException, IOException, SQLException { + // create a mysql database connection + //String myDriver = "org.gjt.mm.mysql.Driver"; + String myUrl = "jdbc:mysql://localhost:3306/couchcleanup"; + Connection conn = DriverManager.getConnection(myUrl, "root", "VA1913wm"); + + FileOutputStream fdup = new FileOutputStream("d:\\filterduplicate.txt"); + FileOutputStream fpers = new FileOutputStream("d:\\filterpersist.txt"); + Scanner s = new Scanner(new File("d:\\all_alerts_with_inactive.txt")); + Map m = new HashMap<>(); + int i = 0; + while (s.hasNextLine()) { + String l = s.nextLine(); + if(StringUtils.isNotBlank(l) && l.startsWith("{\"id\":")){ + JSONObject jo = new JSONObject(l.replace("},", "}")); + System.out.println((++i)+":"+jo); + if(m.containsKey(makeKey(jo.getJSONArray("key")))){ + fdup.write((jo.getString("id")+";,"+jo.getString("key")+"\n\r").getBytes()); + Statement st = conn.createStatement(); + + // note that i'm leaving "date_created" out of this insert statement + st.executeUpdate("INSERT INTO duplicate (`id`,`entityId`,`vaccine`,`key`,`value`)" + + " VALUES ('"+jo.getString("id")+"', " + + "'"+jo.getJSONArray("key").getString(0)+"', " + + "'"+jo.getJSONArray("key").getString(1)+"', " + + "'"+jo.getString("key")+"', " + + "'"+jo.getString("value")+"'); "); + } + else { + m.put(makeKey(jo.getJSONArray("key")), jo); + fpers.write((jo.getString("id")+";,"+jo.getString("key")+"\n\r").getBytes()); + Statement st = conn.createStatement(); + + // note that i'm leaving "date_created" out of this insert statement + st.executeUpdate("INSERT INTO persist (`id`,`entityId`,`vaccine`,`key`,`value`)" + + " VALUES ('"+jo.getString("id")+"', " + + "'"+jo.getJSONArray("key").getString(0)+"', " + + "'"+jo.getJSONArray("key").getString(1)+"', " + + "'"+jo.getString("key")+"', " + + "'"+jo.getString("value")+"'); "); + } + } + } + conn.close(); + fdup.close(); + fpers.close(); + s.close(); + } + + private static String makeKey(JSONArray keyArr) throws JSONException { + return keyArr.getString(0)+":"+keyArr.getString(1); + } + } diff --git a/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java b/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java index e9c86a89b7..9bc6c06594 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java +++ b/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java @@ -24,6 +24,7 @@ public class ApplicationStartupListener implements ApplicationListener