From 10e25c3d7c1bda2b8f496229221ac1c7ee0396b5 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 16 Nov 2022 12:04:57 +0300 Subject: [PATCH 01/27] allow search via post --- .../java/org/opensrp/web/rest/RestUtils.java | 24 +- .../org/opensrp/web/rest/SearchResource.java | 166 ++++++++---- .../org/opensrp/web/utils/SearchHelper.java | 240 +++++++++++++----- .../opensrp/web/rest/SearchResourceTest.java | 11 + .../opensrp/web/utils/SearchHelperTest.java | 110 +++++++- 5 files changed, 442 insertions(+), 109 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 86631fca7..8510dca60 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -4,6 +4,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; +import org.json.JSONObject; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.keycloak.representations.AccessToken; @@ -71,17 +72,32 @@ public static DateTime getDateFilter(String filter, HttpServletRequest req) thro return strval == null ? null : new DateTime(strval); } - public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException { + public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException + { String strval = getStringFilter(filter, req); - if (strval == null) { + if(strval == null){ + return null; + } + if (!strval.contains(":")) { + return new DateTime[] { new DateTime(strval), new DateTime(strval) }; + } + DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); + DateTime d2 = new DateTime(strval.substring(strval.indexOf(":")+1)); + return new DateTime[]{d1,d2}; + } + + public static DateTime[] getDateRangeFilter(String filter, JSONObject jsonObject) throws ParseException + { + String strval = jsonObject.optString(filter); + if(strval.equals("")){ return null; } if (!strval.contains(":")) { return new DateTime[] { new DateTime(strval), new DateTime(strval) }; } DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1)); - return new DateTime[] { d1, d2 }; + DateTime d2 = new DateTime(strval.substring(strval.indexOf(":")+1)); + return new DateTime[]{d1,d2}; } public static boolean getBooleanFilter(String filter, HttpServletRequest req) { diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index d5749ee4b..a2b020fb3 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -4,6 +4,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; +import org.json.JSONObject; import org.opensrp.common.AllConstants.BaseEntity; import org.opensrp.search.ClientSearchBean; import org.opensrp.service.ClientService; @@ -17,6 +18,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -116,6 +118,57 @@ public List search(HttpServletRequest request) throws ParseException {// identifierMap = new HashMap<>(); identifierMap.put(identifierType, identifierValue); } + + searchBean.setIdentifiers(identifierMap); + return searchService.searchClient(searchBean, firstName, middleName, lastName, null); + } + + @RequestMapping(method = RequestMethod.POST, value = "/search", produces = { MediaType.APPLICATION_JSON_VALUE }) + public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params + JSONObject jsonObject = new JSONObject(jsonRequestBody); + String firstName = jsonObject.optString(FIRST_NAME); + String middleName = jsonObject.optString(MIDDLE_NAME); + String lastName = jsonObject.optString(LAST_NAME); + Optional phoneNumber = Optional.ofNullable(jsonObject.optString(PHONE_NUMBER)); + Optional altPhoneNumber = Optional.ofNullable(jsonObject.optString(ALT_PHONE_NUMBER)); + Optional alternateName = Optional.ofNullable(jsonObject.optString(ALT_NAME)); + ClientSearchBean searchBean = new ClientSearchBean(); + searchBean.setNameLike(jsonObject.optString(NAME)); + + searchBean.setGender(jsonObject.optString(GENDER)); + DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + Map attributeMap = new HashMap<>(); + String attributes = jsonObject.optString(ATTRIBUTE); + if (!StringUtils.isBlank(attributes)) { + String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; + String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; + attributeMap.put(attributeType, attributeValue); + } + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); + altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); + alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + searchBean.setAttributes(attributeMap); + + Map identifierMap = null; + String identifiers = jsonObject.optString(IDENTIFIER); + if (!StringUtils.isBlank(identifiers)) { + String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; + String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; + + identifierMap = new HashMap(); + identifierMap.put(identifierType, identifierValue); + } searchBean.setIdentifiers(identifierMap); return searchService.searchClient(searchBean, firstName, middleName, lastName, null); @@ -123,76 +176,101 @@ public List search(HttpServletRequest request) throws ParseException {// @RequestMapping(method = RequestMethod.GET, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) private List searchPathBy(HttpServletRequest request) throws ParseException { - //Process clients search via demographics - ClientSearchBean searchBean = new ClientSearchBean(); - List children = new ArrayList(); + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); - SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); + return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); + } - if (childSearchEntity.isValid()) { - searchBean = childSearchEntity.getClientSearchBean(); - children = searchService.searchGlobalClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), - searchBean.getLastName(), childSearchEntity.getLimit()); - } + @RequestMapping(method = RequestMethod.POST, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) + private List searchPathBy(@RequestBody String jsonRequestBody) throws ParseException { + + JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); + + return searchAndProcess(childSearchEntity, motherSearchEntity,contactPhoneNumber); + + } + + private List searchAndProcess(SearchEntityWrapper childSearchEntity, SearchEntityWrapper motherSearchEntity, + String contactPhoneNumber){ + try { + //Process clients search via demographics + + ClientSearchBean searchBean = new ClientSearchBean(); + List children = new ArrayList(); + if (childSearchEntity.isValid()) { + searchBean = childSearchEntity.getClientSearchBean(); + children = searchService.searchClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), + searchBean.getLastName(), childSearchEntity.getLimit()); + } //Process mothers search via mother demographics - SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); - ClientSearchBean motherSearchBean = new ClientSearchBean(); - List mothers = new ArrayList(); + ClientSearchBean motherSearchBean = new ClientSearchBean(); + List mothers = new ArrayList(); - if (motherSearchEntity.isValid()) { - motherSearchBean = motherSearchEntity.getClientSearchBean(); - mothers = searchService.searchGlobalClient(motherSearchBean, motherSearchBean.getFirstName(), - motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); - } + if (motherSearchEntity.isValid()) { + motherSearchBean = motherSearchEntity.getClientSearchBean(); + mothers = searchService.searchClient(motherSearchBean, motherSearchBean.getFirstName(), + motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); + } - //Process clients search via contact phone number + //Process clients search via contact phone number - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); - List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); + List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); - List eventChildren = clientService.findGlobalByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); + List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); - children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection + children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection - List linkedMothers = new ArrayList(); + List linkedMothers = new ArrayList(); - String RELATIONSHIP_KEY = "mother"; - if (!children.isEmpty()) { - List clientIds = new ArrayList(); - for (Client c : children) { - String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); - if (relationshipId != null && !clientIds.contains(relationshipId)) { - clientIds.add(relationshipId); + String RELATIONSHIP_KEY = "mother"; + if (!children.isEmpty()) { + List clientIds = new ArrayList(); + for (Client c : children) { + String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); + if (relationshipId != null && !clientIds.contains(relationshipId)) { + clientIds.add(relationshipId); + } } - } - linkedMothers = clientService.findGlobalByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); + linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); - } + } - List linkedChildren = new ArrayList(); + List linkedChildren = new ArrayList(); - if (!mothers.isEmpty()) { - for (Client client : mothers) { - linkedChildren.addAll(clientService.findGlobalByRelationship(client.getBaseEntityId())); + if (!mothers.isEmpty()) { + for (Client client : mothers) { + linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); + } } - } - children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection + children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection - for (Client linkedMother : linkedMothers) { - if (!SearchHelper.contains(mothers, linkedMother)) { - mothers.add(linkedMother); + for (Client linkedMother : linkedMothers) { + if (!SearchHelper.contains(mothers, linkedMother)) { + mothers.add(linkedMother); + } } + + return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); + } + catch (Exception e) { - return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); + logger.error("", e); + return new ArrayList(); + } } - + public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuardianPhoneNumber) { List clientBaseEntityIds = new ArrayList(); diff --git a/src/main/java/org/opensrp/web/utils/SearchHelper.java b/src/main/java/org/opensrp/web/utils/SearchHelper.java index bf111db4f..1e2737c15 100644 --- a/src/main/java/org/opensrp/web/utils/SearchHelper.java +++ b/src/main/java/org/opensrp/web/utils/SearchHelper.java @@ -2,6 +2,7 @@ import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; +import org.json.JSONObject; import org.opensrp.search.ClientSearchBean; import org.opensrp.web.rest.RestUtils; import org.smartregister.domain.Client; @@ -18,24 +19,35 @@ public class SearchHelper { - public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { + public static final String ZEIR_ID = "zeir_id"; + public static final String OPENSRP_ID = "opensrp_id"; - ClientSearchBean searchBean = new ClientSearchBean(); + public static final String SIM_PRINT_GUID = "simprints_guid"; - String ZEIR_ID = "zeir_id"; - String OPENSRP_ID = "opensrp_id"; + public static final String FIRST_NAME = "first_name"; + public static final String MIDDLE_NAME = "middle_name"; + public static final String LAST_NAME = "last_name"; + public static final String BIRTH_DATE = "birth_date"; - String SIM_PRINT_GUID = "simprints_guid"; + //Attributes + public static final String INACTIVE = "inactive"; + public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; + public static final String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; + + // Mother + public static final String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; + public static final String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; + public static final String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; + public static final String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; + + public static final String NRC_NUMBER_KEY = "NRC_Number"; + public static final String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; + + public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { + + ClientSearchBean searchBean = new ClientSearchBean(); - String FIRST_NAME = "first_name"; - String MIDDLE_NAME = "middle_name"; - String LAST_NAME = "last_name"; - String BIRTH_DATE = "birth_date"; - //Attributes - String INACTIVE = "inactive"; - String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; - String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; Integer limit = RestUtils.getIntegerFilter("limit", request); if (limit == null || limit.intValue() == 0) { @@ -48,19 +60,11 @@ public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest r searchBean.setLastEditTo(lastEdit[1]); } - String zeirId = RestUtils.getStringFilter(ZEIR_ID, request); - String opensrpId = RestUtils.getStringFilter(OPENSRP_ID, request); - String simprintsGuid = RestUtils.getStringFilter(SIM_PRINT_GUID, request); - searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, request)); searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, request)); searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, request)); searchBean.setGender(RestUtils.getStringFilter(GENDER, request)); - String inActive = RestUtils.getStringFilter(INACTIVE, request); - String lostToFollowUp = RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request); - String nfcCardIdentifier = RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request); - DateTime[] birthdate = RestUtils .getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html @@ -70,39 +74,17 @@ public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest r searchBean.setBirthdateFrom(birthdate[0]); searchBean.setBirthdateTo(birthdate[1]); } - Map identifiers = new HashMap(); - // - if (!StringUtils.isBlank(zeirId)) { - identifiers.put(ZEIR_ID, zeirId); - identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key - } - - if (!StringUtils.isBlank(opensrpId)) { - identifiers.put(OPENSRP_ID, opensrpId); - } - if (!StringUtils.isBlank(simprintsGuid)) { - identifiers.put(SIM_PRINT_GUID, simprintsGuid); - } - - Map attributes = new HashMap(); - if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) - || !StringUtils.isBlank(nfcCardIdentifier)) { - - if (!StringUtils.isBlank(inActive)) { - attributes.put(INACTIVE, inActive); - } - if (!StringUtils.isBlank(lostToFollowUp)) { - attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); - } - if (!StringUtils.isBlank(nfcCardIdentifier)) { - attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant - } - } + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, request)); + commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, request)); + commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, request)); + commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, request)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request)); - searchBean.setIdentifiers(identifiers); - searchBean.setAttributes(attributes); + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); boolean isValid = isSearchValid(searchBean); @@ -115,11 +97,7 @@ public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest Integer limit = setCoreFilters(request, motherSearchBean); - // Mother - String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; - String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; - String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; - String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; + String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, request); String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, request); @@ -127,9 +105,81 @@ public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, request)); motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, request)); - String NRC_NUMBER_KEY = "NRC_Number"; - String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc,compassRelationshipId, motherSearchBean); + + boolean isValid = isSearchValid(motherSearchBean); + + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } + + public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObject) throws ParseException { + + ClientSearchBean searchBean = new ClientSearchBean(); + + Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + if (limit == 0) { + limit = 100; + } + + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + searchBean.setFirstName(jsonObject.optString(FIRST_NAME)); + searchBean.setMiddleName(jsonObject.optString(MIDDLE_NAME)); + searchBean.setLastName(jsonObject.optString(LAST_NAME)); + searchBean.setGender(jsonObject.optString(GENDER)); + + DateTime[] birthdate = RestUtils + .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, jsonObject.optString(ZEIR_ID)); + commonSearchParams.put(OPENSRP_ID, jsonObject.optString(OPENSRP_ID)); + commonSearchParams.put(SIM_PRINT_GUID, jsonObject.optString(SIM_PRINT_GUID)); + commonSearchParams.put(INACTIVE, jsonObject.optString(INACTIVE)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, jsonObject.optString(LOST_TO_FOLLOW_UP)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, jsonObject.optString(NFC_CARD_IDENTIFIER)); + + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); + + boolean isValid = isSearchValid(searchBean); + + return new SearchEntityWrapper(isValid, searchBean, limit); + } + + public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObject) throws ParseException { + + ClientSearchBean motherSearchBean = new ClientSearchBean(); + + Integer limit = setCoreFilters(jsonObject, motherSearchBean); + + String motherGuardianNrc = jsonObject.optString(MOTHER_GUARDIAN_NRC_NUMBER); + String compassRelationshipId = jsonObject.optString(MOTHER_COMPASS_RELATIONSHIP_ID); + + motherSearchBean.setFirstName(jsonObject.optString(MOTHER_GUARDIAN_FIRST_NAME)); + motherSearchBean.setLastName(jsonObject.optString(MOTHER_GUARDIAN_LAST_NAME)); + + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc,compassRelationshipId, motherSearchBean); + + boolean isValid = isSearchValid(motherSearchBean); + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } + + public static void setNameLikeAndAtrributesOnMotherSearchBean(String motherGuardianNrc, + String compassRelationshipId, + ClientSearchBean motherSearchBean){ Map motherAttributes = new HashMap<>(); if (!StringUtils.isBlank(motherGuardianNrc)) { motherAttributes.put(NRC_NUMBER_KEY, motherGuardianNrc); @@ -151,9 +201,50 @@ public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest motherSearchBean.setNameLike(nameLike); motherSearchBean.setAttributes(motherAttributes); - boolean isValid = isSearchValid(motherSearchBean); + } + + public static void setIdentifiersAndAttributeToChildSearchBean(Map commonSearchParams, ClientSearchBean searchBean){ + Map identifiers = new HashMap(); + + String zeirId = commonSearchParams.get(ZEIR_ID); + String opensrpId = commonSearchParams.get(OPENSRP_ID); + String simprintsGuid = commonSearchParams.get(SIM_PRINT_GUID); + String lostToFollowUp = commonSearchParams.get(LOST_TO_FOLLOW_UP); + String inActive = commonSearchParams.get(INACTIVE); + String nfcCardIdentifier = commonSearchParams.get(NFC_CARD_IDENTIFIER); + + if (!StringUtils.isBlank(zeirId)) { + identifiers.put(ZEIR_ID, zeirId); + identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key + } + + if (!StringUtils.isBlank(opensrpId)) { + identifiers.put(OPENSRP_ID, opensrpId); + } + if (!StringUtils.isBlank(simprintsGuid)) { + identifiers.put(SIM_PRINT_GUID, simprintsGuid); + } + + Map attributes = new HashMap(); + if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) + || !StringUtils.isBlank(nfcCardIdentifier)) { + + if (!StringUtils.isBlank(inActive)) { + attributes.put(INACTIVE, inActive); + } + + if (!StringUtils.isBlank(lostToFollowUp)) { + attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); + } + + if (!StringUtils.isBlank(nfcCardIdentifier)) { + attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant + } + } + + searchBean.setIdentifiers(identifiers); + searchBean.setAttributes(attributes); - return new SearchEntityWrapper(isValid, motherSearchBean, limit); } public static Integer setCoreFilters(HttpServletRequest request, ClientSearchBean searchBean) throws ParseException { @@ -172,6 +263,23 @@ public static Integer setCoreFilters(HttpServletRequest request, ClientSearchBea return limit; } + public static Integer setCoreFilters(JSONObject jsonObject, ClientSearchBean searchBean) throws ParseException { + + Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + if (limit == 0) { + limit = 100; + } + + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + return limit; + } + /** * Here we check to see if the search entity param is valid for use in child search Some form of * reflections and custom annotations might have been better @@ -271,6 +379,18 @@ public static String getContactPhoneNumberParam(HttpServletRequest request) { return motherGuardianPhoneNumber; } + public static String getContactPhoneNumberParam(JSONObject jsonObject) { + //Search by mother contact number + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String motherGuardianPhoneNumber = jsonObject.optString(MOTHER_GUARDIAN_PHONE_NUMBER); + motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) + ? jsonObject.optString(CONTACT_PHONE_NUMBER) + : motherGuardianPhoneNumber; + + return motherGuardianPhoneNumber; + } + public static List processSearchResult(List children, List mothers, String RELATIONSHIP_KEY) { List childMotherList = new ArrayList(); diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index a02f90a29..649164629 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -100,4 +100,15 @@ public void shouldSearchClient() throws ParseException { List clients = searchResource.search(mockHttpServletRequest); Assert.assertNotNull(clients); } + + @Test + public void shouldSearchClientPost() throws ParseException { + String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + + "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + + "\"attribute\":\"next_contact_date:2022-06-15\"}"; + SearchResource searchResource=new SearchResource(searchService,clientService,eventService); + List clients = searchResource.searchByPost(jsonRequestString); + Assert.assertNotNull(clients); + + } } diff --git a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java index d43337dc8..523c6538a 100644 --- a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java +++ b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java @@ -1,9 +1,11 @@ package org.opensrp.web.utils; +import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.opensrp.common.util.EasyMap; +import org.opensrp.search.ClientSearchBean; import org.smartregister.domain.Client; import org.springframework.mock.web.MockHttpServletRequest; @@ -250,7 +252,7 @@ public void testProcessSearchResult() { } @Test - public void testMotherSearchParamProcessor() throws ParseException { + public void testMotherSearchParamProcessorForHttpServletRequest() throws ParseException { HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("0"); Mockito.when(httpServletRequest.getParameter("mother_first_name")).thenReturn("Jane"); @@ -266,4 +268,110 @@ public void testMotherSearchParamProcessor() throws ParseException { Assert.assertEquals("2093980", result.get("NRC_Number")); } + @Test + public void testMotherSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("0"); + Mockito.when(jsonObject.optString("mother_first_name")).thenReturn("Jane"); + Mockito.when(jsonObject.optString("mother_last_name")).thenReturn("Doe"); + Mockito.when(jsonObject.optString("mother_nrc_number")).thenReturn("2093980"); + Mockito.when(jsonObject.optString("NRC_Number")).thenReturn("20939801123"); + Mockito.when(jsonObject.optString("mother_compass_relationship_id")).thenReturn("dab102f71bd"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(jsonObject); + Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(2, result.size()); + Assert.assertTrue( result.containsKey("NRC_Number")); + Assert.assertTrue( result.containsKey("Compass_Relationship_ID")); + Assert.assertEquals("2093980", result.get("NRC_Number")); + } + + @Test + public void testChildSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("50"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(jsonObject.optString(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(jsonObject.optString(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(jsonObject.optString(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(jsonObject.optString(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(jsonObject.optString(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(jsonObject); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testChildSearchParamProcessorForHttpServletRequest() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("50"); + Mockito.when(httpServletRequest.getParameter("lastEdited")).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testSetCoreFiltersForJSONObjectWithIntegerLimitReturnsValue(){ + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", 50); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50,result); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testSetCoreFiltersForJSONObjectWithStringLimitReturnsValue(){ + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", "50"); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50,result); + } catch (ParseException e) { + e.printStackTrace(); + } + } + } From 9cc4010659cb341ae310b3c194b63524e4c4ea17 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 16 Nov 2022 15:40:50 +0300 Subject: [PATCH 02/27] rename test methods --- src/test/java/org/opensrp/web/rest/SearchResourceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index 649164629..86b744f07 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -87,7 +87,7 @@ public void testIntersectionMethodReturnsCorrectResult() { } @Test - public void shouldSearchClient() throws ParseException { + public void shouldSearchClientWithGetRequest() throws ParseException { mockHttpServletRequest = new MockHttpServletRequest(); mockHttpServletRequest.addParameter("ff", "ona"); mockHttpServletRequest.addParameter("phone_number", phoneNumber); @@ -102,7 +102,7 @@ public void shouldSearchClient() throws ParseException { } @Test - public void shouldSearchClientPost() throws ParseException { + public void shouldSearchClientWithPostRequest() throws ParseException { String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + "\"attribute\":\"next_contact_date:2022-06-15\"}"; From 93abcba1686fc08ccafdf838f2ddfc3d23e37b91 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Thu, 17 Nov 2022 15:56:45 +0300 Subject: [PATCH 03/27] apply formating --- .../java/org/opensrp/web/rest/RestUtils.java | 383 +++++----- .../org/opensrp/web/rest/SearchResource.java | 546 +++++++------- .../org/opensrp/web/utils/SearchHelper.java | 682 +++++++++--------- .../opensrp/web/rest/SearchResourceTest.java | 128 ++-- .../opensrp/web/utils/SearchHelperTest.java | 624 ++++++++-------- 5 files changed, 1174 insertions(+), 1189 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 8510dca60..1325d4828 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -31,116 +31,108 @@ import java.util.zip.ZipOutputStream; public class RestUtils { - public static final String DATE_FORMAT = "dd-MM-yyyy"; - public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy"); - public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; - public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm"); - - private static final Logger logger = LogManager.getLogger(RestUtils.class.toString()); - - - public static String getStringFilter(String filter, HttpServletRequest req) - { - return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) - { - String filterVal = getStringFilter(filter, req); - if (filterVal != null) { - return Enum.valueOf(cls, filterVal); - } - return null; - } - - public static Integer getIntegerFilter(String filter, HttpServletRequest req) - { - String strval = getStringFilter(filter, req); - return strval == null ? null : Integer.parseInt(strval); - } - - public static Float getFloatFilter(String filter, HttpServletRequest req) - { - String strval = getStringFilter(filter, req); - return strval == null ? null : Float.parseFloat(strval); - } - - public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException - { - String strval = getStringFilter(filter, req); - return strval == null ? null : new DateTime(strval); - } - - public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException - { - String strval = getStringFilter(filter, req); - if(strval == null){ - return null; - } - if (!strval.contains(":")) { - return new DateTime[] { new DateTime(strval), new DateTime(strval) }; - } - DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = new DateTime(strval.substring(strval.indexOf(":")+1)); - return new DateTime[]{d1,d2}; - } - - public static DateTime[] getDateRangeFilter(String filter, JSONObject jsonObject) throws ParseException - { - String strval = jsonObject.optString(filter); - if(strval.equals("")){ - return null; - } - if (!strval.contains(":")) { - return new DateTime[] { new DateTime(strval), new DateTime(strval) }; - } - DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = new DateTime(strval.substring(strval.indexOf(":")+1)); - return new DateTime[]{d1,d2}; - } - - public static boolean getBooleanFilter(String filter, HttpServletRequest req) { - String stringFilter = getStringFilter(filter, req); - return Boolean.parseBoolean(stringFilter); - } - - public static void main(String[] args) { - System.out.println(new DateTime("​1458932400000")); - } - - public static synchronized String setDateFilter(Date date) throws ParseException - { - return date == null ? null : SDF.format(date); - } - - public static void verifyRequiredProperties(List properties, T entity) { - if(properties != null) - for (String p : properties) { - Field[] aaa = entity.getClass().getDeclaredFields(); - for (Field field : aaa) { - if(field.getName().equals(p)){ - field.setAccessible(true); - try { - if(field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")){ - throw new RuntimeException("A required field "+p+" was found empty"); - } - } catch (IllegalArgumentException e) { - e.printStackTrace(); - throw new RuntimeException("A required field "+p+" was not found in resource class"); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - } - } - - public static HttpHeaders getJSONUTF8Headers() { - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add("Content-Type", "application/json; charset=utf-8"); - return responseHeaders; - } + public static final String DATE_FORMAT = "dd-MM-yyyy"; + public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy"); + public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; + public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm"); + + private static final Logger logger = LogManager.getLogger(RestUtils.class.toString()); + + + public static String getStringFilter(String filter, HttpServletRequest req) { + return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) { + String filterVal = getStringFilter(filter, req); + if (filterVal != null) { + return Enum.valueOf(cls, filterVal); + } + return null; + } + + public static Integer getIntegerFilter(String filter, HttpServletRequest req) { + String strval = getStringFilter(filter, req); + return strval == null ? null : Integer.parseInt(strval); + } + + public static Float getFloatFilter(String filter, HttpServletRequest req) { + String strval = getStringFilter(filter, req); + return strval == null ? null : Float.parseFloat(strval); + } + + public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException { + String strval = getStringFilter(filter, req); + return strval == null ? null : new DateTime(strval); + } + + public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException { + String strval = getStringFilter(filter, req); + if (strval == null) { + return null; + } + if (!strval.contains(":")) { + return new DateTime[]{new DateTime(strval), new DateTime(strval)}; + } + DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); + DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1)); + return new DateTime[]{d1, d2}; + } + + public static DateTime[] getDateRangeFilter(String filter, JSONObject jsonObject) throws ParseException { + String strval = jsonObject.optString(filter); + if (strval.equals("")) { + return null; + } + if (!strval.contains(":")) { + return new DateTime[]{new DateTime(strval), new DateTime(strval)}; + } + DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); + DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1)); + return new DateTime[]{d1, d2}; + } + + public static boolean getBooleanFilter(String filter, HttpServletRequest req) { + String stringFilter = getStringFilter(filter, req); + return Boolean.parseBoolean(stringFilter); + } + + public static void main(String[] args) { + System.out.println(new DateTime("​1458932400000")); + } + + public static synchronized String setDateFilter(Date date) throws ParseException { + return date == null ? null : SDF.format(date); + } + + public static void verifyRequiredProperties(List properties, T entity) { + if (properties != null) + for (String p : properties) { + Field[] aaa = entity.getClass().getDeclaredFields(); + for (Field field : aaa) { + if (field.getName().equals(p)) { + field.setAccessible(true); + try { + if (field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")) { + throw new RuntimeException("A required field " + p + " was found empty"); + } + } catch (IllegalArgumentException e) { + e.printStackTrace(); + throw new RuntimeException("A required field " + p + " was not found in resource class"); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + } + + public static HttpHeaders getJSONUTF8Headers() { + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.add("Content-Type", "application/json; charset=utf-8"); + return responseHeaders; + } /** * Zips multimedia files and writes content to {@param zipOutputStream} @@ -149,92 +141,89 @@ public static HttpHeaders getJSONUTF8Headers() { * @param multimediaFiles * @throws IOException */ - public static void zipFiles(ZipOutputStream zipOutputStream, List multimediaFiles, MultimediaFileManager fileManager) throws - IOException { - for (Multimedia multiMedia : multimediaFiles) { - FileInputStream inputStream; - File file = fileManager.retrieveFile(multiMedia.getFilePath()); - if (file != null) { - logger.info("Adding " + file.getName()); - zipOutputStream.putNextEntry(new ZipEntry(file.getName())); - try { - inputStream = new FileInputStream(file); - } catch (FileNotFoundException e) { - logger.warn("Could not find file " + file.getAbsolutePath()); - continue; - } - - // Write the contents of the file - BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); - int data; - while ((data = bufferedInputStream.read()) != -1) { - zipOutputStream.write(data); - } - bufferedInputStream.close(); - zipOutputStream.closeEntry(); - logger.info("Done downloading file " + file.getName()); - - // clean up temp files (may want to cache in future) - if (fileManager instanceof S3MultimediaFileManager) { - file.delete(); - } - } - } - } - - public static User currentUser(Authentication authentication) { - if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) { - @SuppressWarnings("unchecked") - KeycloakPrincipal kp = (KeycloakPrincipal) authentication - .getPrincipal(); - AccessToken token = kp.getKeycloakSecurityContext().getToken(); - User user = new User(authentication.getName()); - user.setPreferredName(token.getName()); - user.setUsername(token.getPreferredUsername()); - List authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority()) - .collect(Collectors.toList()); - user.setAttributes(token.getOtherClaims()); - user.setRoles(authorities); - user.setPermissions(authorities); - return user; - } - return null; - } - - public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException { - File aFile; - FileInputStream fis = null; - ZipEntry zipEntry; - String tempDirectory = System.getProperty("java.io.tmpdir"); - try{ - if(StringUtils.isNotBlank(fileName)) { - aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName); - fis = new FileInputStream(aFile); - zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName); - logger.info("Writing file : '" + fileName + "' to zip file"); - } - else { - fis = new FileInputStream(filePath); - zipEntry = new ZipEntry(filePath); - logger.info("Writing file : '" + filePath + "' to zip file"); - } - zipStream.putNextEntry(zipEntry); - byte[] bytes = new byte[1024]; - int length; - while ((length = fis.read(bytes)) >= 0) { - zipStream.write(bytes, 0, length); - } - - zipStream.closeEntry(); - } - catch (IOException e) { - logger.error("IO Exception occurred: " + e.getMessage()); - } - finally { - if (fis != null) { - fis.close(); - } - } - } + public static void zipFiles(ZipOutputStream zipOutputStream, List multimediaFiles, MultimediaFileManager fileManager) throws + IOException { + for (Multimedia multiMedia : multimediaFiles) { + FileInputStream inputStream; + File file = fileManager.retrieveFile(multiMedia.getFilePath()); + if (file != null) { + logger.info("Adding " + file.getName()); + zipOutputStream.putNextEntry(new ZipEntry(file.getName())); + try { + inputStream = new FileInputStream(file); + } catch (FileNotFoundException e) { + logger.warn("Could not find file " + file.getAbsolutePath()); + continue; + } + + // Write the contents of the file + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + int data; + while ((data = bufferedInputStream.read()) != -1) { + zipOutputStream.write(data); + } + bufferedInputStream.close(); + zipOutputStream.closeEntry(); + logger.info("Done downloading file " + file.getName()); + + // clean up temp files (may want to cache in future) + if (fileManager instanceof S3MultimediaFileManager) { + file.delete(); + } + } + } + } + + public static User currentUser(Authentication authentication) { + if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) { + @SuppressWarnings("unchecked") + KeycloakPrincipal kp = (KeycloakPrincipal) authentication + .getPrincipal(); + AccessToken token = kp.getKeycloakSecurityContext().getToken(); + User user = new User(authentication.getName()); + user.setPreferredName(token.getName()); + user.setUsername(token.getPreferredUsername()); + List authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority()) + .collect(Collectors.toList()); + user.setAttributes(token.getOtherClaims()); + user.setRoles(authorities); + user.setPermissions(authorities); + return user; + } + return null; + } + + public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException { + File aFile; + FileInputStream fis = null; + ZipEntry zipEntry; + String tempDirectory = System.getProperty("java.io.tmpdir"); + try { + if (StringUtils.isNotBlank(fileName)) { + aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName); + fis = new FileInputStream(aFile); + zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName); + logger.info("Writing file : '" + fileName + "' to zip file"); + } else { + fis = new FileInputStream(filePath); + zipEntry = new ZipEntry(filePath); + logger.info("Writing file : '" + filePath + "' to zip file"); + } + zipStream.putNextEntry(zipEntry); + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zipStream.write(bytes, 0, length); + } + + zipStream.closeEntry(); + } catch (IOException e) { + logger.error("IO Exception occurred: " + e.getMessage()); + } finally { + if (fis != null) { + fis.close(); + } + } + } } diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index a2b020fb3..082dd24b9 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -47,278 +47,276 @@ @Controller @RequestMapping(value = "/rest/search") public class SearchResource extends RestResource { - - private static Logger logger = LogManager.getLogger(SearchResource.class.toString()); - - private SearchService searchService; - - private ClientService clientService; - - private EventService eventService; - - @Autowired - public SearchResource(SearchService searchService, ClientService clientService, EventService eventService) { - this.searchService = searchService; - this.clientService = clientService; - this.eventService = eventService; - } - - /** - * @param request - * contains search parameter of with attributes and full colon e.g - * 1. search?attributes=phone_number:072700000 - * or search parameter without attribute and without colon e.g - * 2. search?phone_number=072700000 - * @throws ParseException - */ - @Override - public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params - String firstName = getStringFilter(FIRST_NAME, request); - String middleName = getStringFilter(MIDDLE_NAME, request); - String lastName = getStringFilter(LAST_NAME, request); - Optional phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); - Optional altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); - Optional alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); - ClientSearchBean searchBean = new ClientSearchBean(); - searchBean.setNameLike(getStringFilter(NAME, request)); - - searchBean.setGender(getStringFilter(GENDER, request)); - DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, - request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - Map attributeMap = new HashMap<>(); - String attributes = getStringFilter(ATTRIBUTE, request); - if (!StringUtils.isBlank(attributes)) { - String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; - String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; - attributeMap.put(attributeType, attributeValue); - } - phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); - altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); - alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); - searchBean.setAttributes(attributeMap); - - Map identifierMap = null; - String identifiers = getStringFilter(IDENTIFIER, request); - if (!StringUtils.isBlank(identifiers)) { - String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; - String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; - - identifierMap = new HashMap<>(); - identifierMap.put(identifierType, identifierValue); - } - - searchBean.setIdentifiers(identifierMap); - return searchService.searchClient(searchBean, firstName, middleName, lastName, null); - } - - @RequestMapping(method = RequestMethod.POST, value = "/search", produces = { MediaType.APPLICATION_JSON_VALUE }) - public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params - JSONObject jsonObject = new JSONObject(jsonRequestBody); - String firstName = jsonObject.optString(FIRST_NAME); - String middleName = jsonObject.optString(MIDDLE_NAME); - String lastName = jsonObject.optString(LAST_NAME); - Optional phoneNumber = Optional.ofNullable(jsonObject.optString(PHONE_NUMBER)); - Optional altPhoneNumber = Optional.ofNullable(jsonObject.optString(ALT_PHONE_NUMBER)); - Optional alternateName = Optional.ofNullable(jsonObject.optString(ALT_NAME)); - ClientSearchBean searchBean = new ClientSearchBean(); - searchBean.setNameLike(jsonObject.optString(NAME)); - - searchBean.setGender(jsonObject.optString(GENDER)); - DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - Map attributeMap = new HashMap<>(); - String attributes = jsonObject.optString(ATTRIBUTE); - if (!StringUtils.isBlank(attributes)) { - String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; - String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; - attributeMap.put(attributeType, attributeValue); - } - phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); - altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); - alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); - searchBean.setAttributes(attributeMap); - - Map identifierMap = null; - String identifiers = jsonObject.optString(IDENTIFIER); - if (!StringUtils.isBlank(identifiers)) { - String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; - String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; - - identifierMap = new HashMap(); - identifierMap.put(identifierType, identifierValue); - } - - searchBean.setIdentifiers(identifierMap); - return searchService.searchClient(searchBean, firstName, middleName, lastName, null); - } - - @RequestMapping(method = RequestMethod.GET, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) - private List searchPathBy(HttpServletRequest request) throws ParseException { - - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); - SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); - SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); - - return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); - } - - @RequestMapping(method = RequestMethod.POST, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) - private List searchPathBy(@RequestBody String jsonRequestBody) throws ParseException { - - JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); - SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); - SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); - - return searchAndProcess(childSearchEntity, motherSearchEntity,contactPhoneNumber); - - } - - private List searchAndProcess(SearchEntityWrapper childSearchEntity, SearchEntityWrapper motherSearchEntity, - String contactPhoneNumber){ - try { - //Process clients search via demographics - - ClientSearchBean searchBean = new ClientSearchBean(); - List children = new ArrayList(); - if (childSearchEntity.isValid()) { - searchBean = childSearchEntity.getClientSearchBean(); - children = searchService.searchClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), - searchBean.getLastName(), childSearchEntity.getLimit()); - } - - //Process mothers search via mother demographics - - ClientSearchBean motherSearchBean = new ClientSearchBean(); - List mothers = new ArrayList(); - - if (motherSearchEntity.isValid()) { - motherSearchBean = motherSearchEntity.getClientSearchBean(); - mothers = searchService.searchClient(motherSearchBean, motherSearchBean.getFirstName(), - motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); - } - - //Process clients search via contact phone number - - - List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); - - List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); - - children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection - - List linkedMothers = new ArrayList(); - - String RELATIONSHIP_KEY = "mother"; - if (!children.isEmpty()) { - List clientIds = new ArrayList(); - for (Client c : children) { - String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); - if (relationshipId != null && !clientIds.contains(relationshipId)) { - clientIds.add(relationshipId); - } - } - - linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); - - } - - List linkedChildren = new ArrayList(); - - if (!mothers.isEmpty()) { - for (Client client : mothers) { - linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); - } - } - - children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection - - for (Client linkedMother : linkedMothers) { - if (!SearchHelper.contains(mothers, linkedMother)) { - mothers.add(linkedMother); - } - } - - return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); - - } - catch (Exception e) { - - logger.error("", e); - return new ArrayList(); - } - } - - public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuardianPhoneNumber) { - List clientBaseEntityIds = new ArrayList(); - - if (!StringUtils.isBlank(motherGuardianPhoneNumber)) { - - List events = eventService.findEventsByConceptAndValue("159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", - motherGuardianPhoneNumber); - if (events != null && !events.isEmpty()) { - for (Event event : events) { - String entityId = event.getBaseEntityId(); - if (entityId != null && !clientBaseEntityIds.contains(entityId)) { - clientBaseEntityIds.add(entityId); - } - } - - } - } - return clientBaseEntityIds; - } - - @Override - public List filter(String query) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client getByUniqueId(String uniqueId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List requiredProperties() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client create(Client entity) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client update(Client entity) { - // TODO Auto-generated method stub - return null; - } - + + private static Logger logger = LogManager.getLogger(SearchResource.class.toString()); + + private SearchService searchService; + + private ClientService clientService; + + private EventService eventService; + + @Autowired + public SearchResource(SearchService searchService, ClientService clientService, EventService eventService) { + this.searchService = searchService; + this.clientService = clientService; + this.eventService = eventService; + } + + /** + * @param request contains search parameter of with attributes and full colon e.g + * 1. search?attributes=phone_number:072700000 + * or search parameter without attribute and without colon e.g + * 2. search?phone_number=072700000 + * @throws ParseException + */ + @Override + public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params + String firstName = getStringFilter(FIRST_NAME, request); + String middleName = getStringFilter(MIDDLE_NAME, request); + String lastName = getStringFilter(LAST_NAME, request); + Optional phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); + Optional altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); + Optional alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); + ClientSearchBean searchBean = new ClientSearchBean(); + searchBean.setNameLike(getStringFilter(NAME, request)); + + searchBean.setGender(getStringFilter(GENDER, request)); + DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, + request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + Map attributeMap = new HashMap<>(); + String attributes = getStringFilter(ATTRIBUTE, request); + if (!StringUtils.isBlank(attributes)) { + String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; + String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; + attributeMap.put(attributeType, attributeValue); + } + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); + altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); + alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + searchBean.setAttributes(attributeMap); + + Map identifierMap = null; + String identifiers = getStringFilter(IDENTIFIER, request); + if (!StringUtils.isBlank(identifiers)) { + String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; + String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; + + identifierMap = new HashMap<>(); + identifierMap.put(identifierType, identifierValue); + } + + searchBean.setIdentifiers(identifierMap); + return searchService.searchClient(searchBean, firstName, middleName, lastName, null); + } + + @RequestMapping(method = RequestMethod.POST, value = "/search", produces = {MediaType.APPLICATION_JSON_VALUE}) + public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params + JSONObject jsonObject = new JSONObject(jsonRequestBody); + String firstName = jsonObject.optString(FIRST_NAME); + String middleName = jsonObject.optString(MIDDLE_NAME); + String lastName = jsonObject.optString(LAST_NAME); + Optional phoneNumber = Optional.ofNullable(jsonObject.optString(PHONE_NUMBER)); + Optional altPhoneNumber = Optional.ofNullable(jsonObject.optString(ALT_PHONE_NUMBER)); + Optional alternateName = Optional.ofNullable(jsonObject.optString(ALT_NAME)); + ClientSearchBean searchBean = new ClientSearchBean(); + searchBean.setNameLike(jsonObject.optString(NAME)); + + searchBean.setGender(jsonObject.optString(GENDER)); + DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + Map attributeMap = new HashMap<>(); + String attributes = jsonObject.optString(ATTRIBUTE); + if (!StringUtils.isBlank(attributes)) { + String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; + String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; + attributeMap.put(attributeType, attributeValue); + } + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); + altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); + alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + searchBean.setAttributes(attributeMap); + + Map identifierMap = null; + String identifiers = jsonObject.optString(IDENTIFIER); + if (!StringUtils.isBlank(identifiers)) { + String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; + String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; + + identifierMap = new HashMap(); + identifierMap.put(identifierType, identifierValue); + } + + searchBean.setIdentifiers(identifierMap); + return searchService.searchClient(searchBean, firstName, middleName, lastName, null); + } + + @RequestMapping(method = RequestMethod.GET, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) + private List searchPathBy(HttpServletRequest request) throws ParseException { + + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); + + return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); + } + + @RequestMapping(method = RequestMethod.POST, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) + private List searchPathBy(@RequestBody String jsonRequestBody) throws ParseException { + + JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); + + return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); + + } + + private List searchAndProcess(SearchEntityWrapper childSearchEntity, SearchEntityWrapper motherSearchEntity, + String contactPhoneNumber) { + try { + //Process clients search via demographics + + ClientSearchBean searchBean = new ClientSearchBean(); + List children = new ArrayList(); + if (childSearchEntity.isValid()) { + searchBean = childSearchEntity.getClientSearchBean(); + children = searchService.searchClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), + searchBean.getLastName(), childSearchEntity.getLimit()); + } + + //Process mothers search via mother demographics + + ClientSearchBean motherSearchBean = new ClientSearchBean(); + List mothers = new ArrayList(); + + if (motherSearchEntity.isValid()) { + motherSearchBean = motherSearchEntity.getClientSearchBean(); + mothers = searchService.searchClient(motherSearchBean, motherSearchBean.getFirstName(), + motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); + } + + //Process clients search via contact phone number + + + List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); + + List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); + + children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection + + List linkedMothers = new ArrayList(); + + String RELATIONSHIP_KEY = "mother"; + if (!children.isEmpty()) { + List clientIds = new ArrayList(); + for (Client c : children) { + String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); + if (relationshipId != null && !clientIds.contains(relationshipId)) { + clientIds.add(relationshipId); + } + } + + linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); + + } + + List linkedChildren = new ArrayList(); + + if (!mothers.isEmpty()) { + for (Client client : mothers) { + linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); + } + } + + children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection + + for (Client linkedMother : linkedMothers) { + if (!SearchHelper.contains(mothers, linkedMother)) { + mothers.add(linkedMother); + } + } + + return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); + + } catch (Exception e) { + + logger.error("", e); + return new ArrayList(); + } + } + + public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuardianPhoneNumber) { + List clientBaseEntityIds = new ArrayList(); + + if (!StringUtils.isBlank(motherGuardianPhoneNumber)) { + + List events = eventService.findEventsByConceptAndValue("159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + motherGuardianPhoneNumber); + if (events != null && !events.isEmpty()) { + for (Event event : events) { + String entityId = event.getBaseEntityId(); + if (entityId != null && !clientBaseEntityIds.contains(entityId)) { + clientBaseEntityIds.add(entityId); + } + } + + } + } + return clientBaseEntityIds; + } + + @Override + public List filter(String query) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client getByUniqueId(String uniqueId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List requiredProperties() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client create(Client entity) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client update(Client entity) { + // TODO Auto-generated method stub + return null; + } + } diff --git a/src/main/java/org/opensrp/web/utils/SearchHelper.java b/src/main/java/org/opensrp/web/utils/SearchHelper.java index 1e2737c15..d34930572 100644 --- a/src/main/java/org/opensrp/web/utils/SearchHelper.java +++ b/src/main/java/org/opensrp/web/utils/SearchHelper.java @@ -19,408 +19,406 @@ public class SearchHelper { - public static final String ZEIR_ID = "zeir_id"; - public static final String OPENSRP_ID = "opensrp_id"; + public static final String ZEIR_ID = "zeir_id"; + public static final String OPENSRP_ID = "opensrp_id"; - public static final String SIM_PRINT_GUID = "simprints_guid"; + public static final String SIM_PRINT_GUID = "simprints_guid"; - public static final String FIRST_NAME = "first_name"; - public static final String MIDDLE_NAME = "middle_name"; - public static final String LAST_NAME = "last_name"; - public static final String BIRTH_DATE = "birth_date"; + public static final String FIRST_NAME = "first_name"; + public static final String MIDDLE_NAME = "middle_name"; + public static final String LAST_NAME = "last_name"; + public static final String BIRTH_DATE = "birth_date"; - //Attributes - public static final String INACTIVE = "inactive"; - public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; - public static final String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; + //Attributes + public static final String INACTIVE = "inactive"; + public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; + public static final String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; - // Mother - public static final String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; - public static final String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; - public static final String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; - public static final String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; + // Mother + public static final String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; + public static final String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; + public static final String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; + public static final String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; - public static final String NRC_NUMBER_KEY = "NRC_Number"; - public static final String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; + public static final String NRC_NUMBER_KEY = "NRC_Number"; + public static final String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; - public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { + public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { - ClientSearchBean searchBean = new ClientSearchBean(); + ClientSearchBean searchBean = new ClientSearchBean(); + Integer limit = RestUtils.getIntegerFilter("limit", request); + if (limit == null || limit.intValue() == 0) { + limit = 100; + } - Integer limit = RestUtils.getIntegerFilter("limit", request); - if (limit == null || limit.intValue() == 0) { - limit = 100; - } + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } + searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, request)); + searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, request)); + searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, request)); + searchBean.setGender(RestUtils.getStringFilter(GENDER, request)); - searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, request)); - searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, request)); - searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, request)); - searchBean.setGender(RestUtils.getStringFilter(GENDER, request)); + DateTime[] birthdate = RestUtils + .getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - DateTime[] birthdate = RestUtils - .getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, request)); + commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, request)); + commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, request)); + commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, request)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request)); - Map commonSearchParams = new HashMap<>(); - commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, request)); - commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, request)); - commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, request)); - commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, request)); - commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request)); - commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request)); + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); - setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); + boolean isValid = isSearchValid(searchBean); - boolean isValid = isSearchValid(searchBean); + return new SearchEntityWrapper(isValid, searchBean, limit); + } - return new SearchEntityWrapper(isValid, searchBean, limit); - } + public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest request) throws ParseException { - public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest request) throws ParseException { + ClientSearchBean motherSearchBean = new ClientSearchBean(); - ClientSearchBean motherSearchBean = new ClientSearchBean(); + Integer limit = setCoreFilters(request, motherSearchBean); - Integer limit = setCoreFilters(request, motherSearchBean); + String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, request); + String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, request); + motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, request)); + motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, request)); - String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, request); - String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, request); + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); - motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, request)); - motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, request)); + boolean isValid = isSearchValid(motherSearchBean); - setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc,compassRelationshipId, motherSearchBean); + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } - boolean isValid = isSearchValid(motherSearchBean); + public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObject) throws ParseException { - return new SearchEntityWrapper(isValid, motherSearchBean, limit); - } + ClientSearchBean searchBean = new ClientSearchBean(); - public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObject) throws ParseException { + Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + if (limit == 0) { + limit = 100; + } - ClientSearchBean searchBean = new ClientSearchBean(); + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } - Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) - : jsonObject.optInt("limit"); - if (limit == 0) { - limit = 100; - } + searchBean.setFirstName(jsonObject.optString(FIRST_NAME)); + searchBean.setMiddleName(jsonObject.optString(MIDDLE_NAME)); + searchBean.setLastName(jsonObject.optString(LAST_NAME)); + searchBean.setGender(jsonObject.optString(GENDER)); - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } + DateTime[] birthdate = RestUtils + .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - searchBean.setFirstName(jsonObject.optString(FIRST_NAME)); - searchBean.setMiddleName(jsonObject.optString(MIDDLE_NAME)); - searchBean.setLastName(jsonObject.optString(LAST_NAME)); - searchBean.setGender(jsonObject.optString(GENDER)); + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - DateTime[] birthdate = RestUtils - .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, jsonObject.optString(ZEIR_ID)); + commonSearchParams.put(OPENSRP_ID, jsonObject.optString(OPENSRP_ID)); + commonSearchParams.put(SIM_PRINT_GUID, jsonObject.optString(SIM_PRINT_GUID)); + commonSearchParams.put(INACTIVE, jsonObject.optString(INACTIVE)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, jsonObject.optString(LOST_TO_FOLLOW_UP)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, jsonObject.optString(NFC_CARD_IDENTIFIER)); - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); - Map commonSearchParams = new HashMap<>(); - commonSearchParams.put(ZEIR_ID, jsonObject.optString(ZEIR_ID)); - commonSearchParams.put(OPENSRP_ID, jsonObject.optString(OPENSRP_ID)); - commonSearchParams.put(SIM_PRINT_GUID, jsonObject.optString(SIM_PRINT_GUID)); - commonSearchParams.put(INACTIVE, jsonObject.optString(INACTIVE)); - commonSearchParams.put(LOST_TO_FOLLOW_UP, jsonObject.optString(LOST_TO_FOLLOW_UP)); - commonSearchParams.put(NFC_CARD_IDENTIFIER, jsonObject.optString(NFC_CARD_IDENTIFIER)); + boolean isValid = isSearchValid(searchBean); - setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); + return new SearchEntityWrapper(isValid, searchBean, limit); + } - boolean isValid = isSearchValid(searchBean); + public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObject) throws ParseException { - return new SearchEntityWrapper(isValid, searchBean, limit); - } + ClientSearchBean motherSearchBean = new ClientSearchBean(); - public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObject) throws ParseException { + Integer limit = setCoreFilters(jsonObject, motherSearchBean); - ClientSearchBean motherSearchBean = new ClientSearchBean(); + String motherGuardianNrc = jsonObject.optString(MOTHER_GUARDIAN_NRC_NUMBER); + String compassRelationshipId = jsonObject.optString(MOTHER_COMPASS_RELATIONSHIP_ID); - Integer limit = setCoreFilters(jsonObject, motherSearchBean); + motherSearchBean.setFirstName(jsonObject.optString(MOTHER_GUARDIAN_FIRST_NAME)); + motherSearchBean.setLastName(jsonObject.optString(MOTHER_GUARDIAN_LAST_NAME)); - String motherGuardianNrc = jsonObject.optString(MOTHER_GUARDIAN_NRC_NUMBER); - String compassRelationshipId = jsonObject.optString(MOTHER_COMPASS_RELATIONSHIP_ID); + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); - motherSearchBean.setFirstName(jsonObject.optString(MOTHER_GUARDIAN_FIRST_NAME)); - motherSearchBean.setLastName(jsonObject.optString(MOTHER_GUARDIAN_LAST_NAME)); + boolean isValid = isSearchValid(motherSearchBean); - setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc,compassRelationshipId, motherSearchBean); + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } - boolean isValid = isSearchValid(motherSearchBean); + public static void setNameLikeAndAtrributesOnMotherSearchBean(String motherGuardianNrc, + String compassRelationshipId, + ClientSearchBean motherSearchBean) { + Map motherAttributes = new HashMap<>(); + if (!StringUtils.isBlank(motherGuardianNrc)) { + motherAttributes.put(NRC_NUMBER_KEY, motherGuardianNrc); + } + if (!StringUtils.isBlank(compassRelationshipId)) { + motherAttributes.put(COMPASS_RELATIONSHIP_ID, compassRelationshipId); + } - return new SearchEntityWrapper(isValid, motherSearchBean, limit); - } + String nameLike = null; - public static void setNameLikeAndAtrributesOnMotherSearchBean(String motherGuardianNrc, - String compassRelationshipId, - ClientSearchBean motherSearchBean){ - Map motherAttributes = new HashMap<>(); - if (!StringUtils.isBlank(motherGuardianNrc)) { - motherAttributes.put(NRC_NUMBER_KEY, motherGuardianNrc); - } - if (!StringUtils.isBlank(compassRelationshipId)) { - motherAttributes.put(COMPASS_RELATIONSHIP_ID, compassRelationshipId); - } + if (!StringUtils.isBlank(motherSearchBean.getFirstName()) + && StringUtils.containsWhitespace(motherSearchBean.getFirstName().trim()) + && StringUtils.isBlank(motherSearchBean.getLastName())) { + String[] arr = motherSearchBean.getFirstName().split("\\s+"); + nameLike = arr[0]; + motherSearchBean.setFirstName(null); + } - String nameLike = null; + motherSearchBean.setNameLike(nameLike); + motherSearchBean.setAttributes(motherAttributes); - if (!StringUtils.isBlank(motherSearchBean.getFirstName()) - && StringUtils.containsWhitespace(motherSearchBean.getFirstName().trim()) - && StringUtils.isBlank(motherSearchBean.getLastName())) { - String[] arr = motherSearchBean.getFirstName().split("\\s+"); - nameLike = arr[0]; - motherSearchBean.setFirstName(null); - } + } - motherSearchBean.setNameLike(nameLike); - motherSearchBean.setAttributes(motherAttributes); + public static void setIdentifiersAndAttributeToChildSearchBean(Map commonSearchParams, ClientSearchBean searchBean) { + Map identifiers = new HashMap(); - } + String zeirId = commonSearchParams.get(ZEIR_ID); + String opensrpId = commonSearchParams.get(OPENSRP_ID); + String simprintsGuid = commonSearchParams.get(SIM_PRINT_GUID); + String lostToFollowUp = commonSearchParams.get(LOST_TO_FOLLOW_UP); + String inActive = commonSearchParams.get(INACTIVE); + String nfcCardIdentifier = commonSearchParams.get(NFC_CARD_IDENTIFIER); + + if (!StringUtils.isBlank(zeirId)) { + identifiers.put(ZEIR_ID, zeirId); + identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key + } + + if (!StringUtils.isBlank(opensrpId)) { + identifiers.put(OPENSRP_ID, opensrpId); + } + if (!StringUtils.isBlank(simprintsGuid)) { + identifiers.put(SIM_PRINT_GUID, simprintsGuid); + } + + Map attributes = new HashMap(); + if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) + || !StringUtils.isBlank(nfcCardIdentifier)) { + + if (!StringUtils.isBlank(inActive)) { + attributes.put(INACTIVE, inActive); + } - public static void setIdentifiersAndAttributeToChildSearchBean(Map commonSearchParams, ClientSearchBean searchBean){ - Map identifiers = new HashMap(); + if (!StringUtils.isBlank(lostToFollowUp)) { + attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); + } + + if (!StringUtils.isBlank(nfcCardIdentifier)) { + attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant + } + } - String zeirId = commonSearchParams.get(ZEIR_ID); - String opensrpId = commonSearchParams.get(OPENSRP_ID); - String simprintsGuid = commonSearchParams.get(SIM_PRINT_GUID); - String lostToFollowUp = commonSearchParams.get(LOST_TO_FOLLOW_UP); - String inActive = commonSearchParams.get(INACTIVE); - String nfcCardIdentifier = commonSearchParams.get(NFC_CARD_IDENTIFIER); - - if (!StringUtils.isBlank(zeirId)) { - identifiers.put(ZEIR_ID, zeirId); - identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key - } - - if (!StringUtils.isBlank(opensrpId)) { - identifiers.put(OPENSRP_ID, opensrpId); - } - if (!StringUtils.isBlank(simprintsGuid)) { - identifiers.put(SIM_PRINT_GUID, simprintsGuid); - } - - Map attributes = new HashMap(); - if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) - || !StringUtils.isBlank(nfcCardIdentifier)) { - - if (!StringUtils.isBlank(inActive)) { - attributes.put(INACTIVE, inActive); - } + searchBean.setIdentifiers(identifiers); + searchBean.setAttributes(attributes); - if (!StringUtils.isBlank(lostToFollowUp)) { - attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); - } - - if (!StringUtils.isBlank(nfcCardIdentifier)) { - attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant - } - } + } - searchBean.setIdentifiers(identifiers); - searchBean.setAttributes(attributes); + public static Integer setCoreFilters(HttpServletRequest request, ClientSearchBean searchBean) throws ParseException { - } + Integer limit = RestUtils.getIntegerFilter("limit", request); + if (limit == null || limit.intValue() == 0) { + limit = 100; + } - public static Integer setCoreFilters(HttpServletRequest request, ClientSearchBean searchBean) throws ParseException { + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } - Integer limit = RestUtils.getIntegerFilter("limit", request); - if (limit == null || limit.intValue() == 0) { - limit = 100; - } - - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - return limit; - } - - public static Integer setCoreFilters(JSONObject jsonObject, ClientSearchBean searchBean) throws ParseException { - - Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) - : jsonObject.optInt("limit"); - if (limit == 0) { - limit = 100; - } - - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - return limit; - } - - /** - * Here we check to see if the search entity param is valid for use in child search Some form of - * reflections and custom annotations might have been better - * - * @param searchBean model with search params - * @return boolean whether the search entity is valid - */ - - public static boolean isSearchValid(ClientSearchBean searchBean) { - - return !StringUtils.isBlank(searchBean.getFirstName()) - || !StringUtils.isBlank(searchBean.getMiddleName()) - || !StringUtils.isBlank(searchBean.getLastName()) - || !StringUtils.isBlank(searchBean.getGender()) - || (searchBean.getAttributes() != null && !searchBean.getAttributes().isEmpty()) - || searchBean.getBirthdateFrom() != null || searchBean.getBirthdateTo() != null - || searchBean.getLastEditFrom() != null || searchBean.getLastEditTo() != null - || (searchBean.getIdentifiers() != null && !searchBean.getIdentifiers().isEmpty()) - || !StringUtils.isBlank(searchBean.getNameLike()); - - } - - /** - * // Method returns the intersection of two lists - * - * @param list1_ - * @param list2_ - * @return merged intersection list - */ - public static List intersection(List list1_, List list2_) { - - List list1 = list1_; - List list2 = list2_; - - list1 = createClientListIfEmpty(list1); - - list2 = createClientListIfEmpty(list2); - - if (list1.isEmpty() && list2.isEmpty()) { - return new ArrayList(); - } - - if (list1.isEmpty() && !list2.isEmpty()) { - return list2; - } - - if (list2.isEmpty() && !list1.isEmpty()) { - return list1; - } - - List list = new ArrayList(); - - for (Client t : list1) { - if (contains(list2, t)) { - list.add(t); - } - } - - return list; - } - - public static List createClientListIfEmpty(List list_) { - List list = list_; - - if (list == null) { - list = new ArrayList(); - } - - return list; - } - - public static boolean contains(List clients, Client c) { - if (clients == null || clients.isEmpty() || c == null || c.getBaseEntityId() == null) { - return false; - } - for (Client client : clients) { - - if (client != null && client.getBaseEntityId() != null - && c.getBaseEntityId().equals(client.getBaseEntityId())) { - - return true; - - } - } - return false; - } - - public static String getContactPhoneNumberParam(HttpServletRequest request) { - //Search by mother contact number - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; - String motherGuardianPhoneNumber = RestUtils.getStringFilter(MOTHER_GUARDIAN_PHONE_NUMBER, request); - motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) - ? RestUtils.getStringFilter(CONTACT_PHONE_NUMBER, request) - : motherGuardianPhoneNumber; - - return motherGuardianPhoneNumber; - } - - public static String getContactPhoneNumberParam(JSONObject jsonObject) { - //Search by mother contact number - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; - String motherGuardianPhoneNumber = jsonObject.optString(MOTHER_GUARDIAN_PHONE_NUMBER); - motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) - ? jsonObject.optString(CONTACT_PHONE_NUMBER) - : motherGuardianPhoneNumber; - - return motherGuardianPhoneNumber; - } - - public static List processSearchResult(List children, List mothers, - String RELATIONSHIP_KEY) { - List childMotherList = new ArrayList(); - for (Client child : children) { - for (Client mother : mothers) { - String relationalId = getRelationalId(child, RELATIONSHIP_KEY); - String motherEntityId = mother.getBaseEntityId(); - if (relationalId != null && relationalId.equalsIgnoreCase(motherEntityId)) { - childMotherList.add(new ChildMother(child, mother)); - } - } - } - - return childMotherList; - } - - public static String getRelationalId(Client c, String relationshipKey) { - Map> relationships = c.getRelationships(); - if (relationships != null) { - for (Map.Entry> entry : relationships.entrySet()) { - String key = entry.getKey(); - if (key.equalsIgnoreCase(relationshipKey)) { - List rList = entry.getValue(); - if (!rList.isEmpty()) { - return rList.get(0); - } - } - } - } - - return null; - } + return limit; + } + + public static Integer setCoreFilters(JSONObject jsonObject, ClientSearchBean searchBean) throws ParseException { + + Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + if (limit == 0) { + limit = 100; + } + + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + return limit; + } + + /** + * Here we check to see if the search entity param is valid for use in child search Some form of + * reflections and custom annotations might have been better + * + * @param searchBean model with search params + * @return boolean whether the search entity is valid + */ + + public static boolean isSearchValid(ClientSearchBean searchBean) { + + return !StringUtils.isBlank(searchBean.getFirstName()) + || !StringUtils.isBlank(searchBean.getMiddleName()) + || !StringUtils.isBlank(searchBean.getLastName()) + || !StringUtils.isBlank(searchBean.getGender()) + || (searchBean.getAttributes() != null && !searchBean.getAttributes().isEmpty()) + || searchBean.getBirthdateFrom() != null || searchBean.getBirthdateTo() != null + || searchBean.getLastEditFrom() != null || searchBean.getLastEditTo() != null + || (searchBean.getIdentifiers() != null && !searchBean.getIdentifiers().isEmpty()) + || !StringUtils.isBlank(searchBean.getNameLike()); + + } + + /** + * // Method returns the intersection of two lists + * + * @param list1_ + * @param list2_ + * @return merged intersection list + */ + public static List intersection(List list1_, List list2_) { + + List list1 = list1_; + List list2 = list2_; + + list1 = createClientListIfEmpty(list1); + + list2 = createClientListIfEmpty(list2); + + if (list1.isEmpty() && list2.isEmpty()) { + return new ArrayList(); + } + + if (list1.isEmpty() && !list2.isEmpty()) { + return list2; + } + + if (list2.isEmpty() && !list1.isEmpty()) { + return list1; + } + + List list = new ArrayList(); + + for (Client t : list1) { + if (contains(list2, t)) { + list.add(t); + } + } + + return list; + } + + public static List createClientListIfEmpty(List list_) { + List list = list_; + + if (list == null) { + list = new ArrayList(); + } + + return list; + } + + public static boolean contains(List clients, Client c) { + if (clients == null || clients.isEmpty() || c == null || c.getBaseEntityId() == null) { + return false; + } + for (Client client : clients) { + + if (client != null && client.getBaseEntityId() != null + && c.getBaseEntityId().equals(client.getBaseEntityId())) { + + return true; + + } + } + return false; + } + + public static String getContactPhoneNumberParam(HttpServletRequest request) { + //Search by mother contact number + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String motherGuardianPhoneNumber = RestUtils.getStringFilter(MOTHER_GUARDIAN_PHONE_NUMBER, request); + motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) + ? RestUtils.getStringFilter(CONTACT_PHONE_NUMBER, request) + : motherGuardianPhoneNumber; + + return motherGuardianPhoneNumber; + } + + public static String getContactPhoneNumberParam(JSONObject jsonObject) { + //Search by mother contact number + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String motherGuardianPhoneNumber = jsonObject.optString(MOTHER_GUARDIAN_PHONE_NUMBER); + motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) + ? jsonObject.optString(CONTACT_PHONE_NUMBER) + : motherGuardianPhoneNumber; + + return motherGuardianPhoneNumber; + } + + public static List processSearchResult(List children, List mothers, + String RELATIONSHIP_KEY) { + List childMotherList = new ArrayList(); + for (Client child : children) { + for (Client mother : mothers) { + String relationalId = getRelationalId(child, RELATIONSHIP_KEY); + String motherEntityId = mother.getBaseEntityId(); + if (relationalId != null && relationalId.equalsIgnoreCase(motherEntityId)) { + childMotherList.add(new ChildMother(child, mother)); + } + } + } + + return childMotherList; + } + + public static String getRelationalId(Client c, String relationshipKey) { + Map> relationships = c.getRelationships(); + if (relationships != null) { + for (Map.Entry> entry : relationships.entrySet()) { + String key = entry.getKey(); + if (key.equalsIgnoreCase(relationshipKey)) { + List rList = entry.getValue(); + if (!rList.isEmpty()) { + return rList.get(0); + } + } + } + } + + return null; + } } diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index 86b744f07..fc1521ba3 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -12,7 +12,11 @@ import org.opensrp.repository.EventsRepository; import org.opensrp.repository.PlanRepository; import org.opensrp.repository.SearchRepository; -import org.opensrp.service.*; +import org.opensrp.service.ClientService; +import org.opensrp.service.EventService; +import org.opensrp.service.ExportEventDataMapper; +import org.opensrp.service.SearchService; +import org.opensrp.service.TaskGenerator; import org.opensrp.web.rest.it.TestWebContextLoader; import org.opensrp.web.utils.SearchHelper; import org.smartregister.domain.Client; @@ -27,88 +31,84 @@ import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = TestWebContextLoader.class, locations = { "classpath:test-webmvc-config.xml", }) +@ContextConfiguration(loader = TestWebContextLoader.class, locations = {"classpath:test-webmvc-config.xml",}) public class SearchResourceTest { - @Autowired - protected WebApplicationContext webApplicationContext; + @Autowired + protected WebApplicationContext webApplicationContext; - private SearchService searchService; + private SearchService searchService; - private ClientService clientService; + private ClientService clientService; - private EventService eventService; + private EventService eventService; - private ExportEventDataMapper exportEventDataMapper; + private ExportEventDataMapper exportEventDataMapper; - private TaskGenerator taskGenerator; + private TaskGenerator taskGenerator; - private PlanRepository planRepository; - MockHttpServletRequest mockHttpServletRequest; - String phoneNumber = "0727000000"; - String town = "town"; + private PlanRepository planRepository; - String firstName = "name"; + MockHttpServletRequest mockHttpServletRequest; + String phoneNumber = "0727000000"; + String firstName = "name"; + DateTime birthDate = new DateTime(0l, DateTimeZone.UTC); - String male = "male"; - DateTime birthDate = new DateTime(0l, DateTimeZone.UTC); + @Before + public void setUp() { + SearchRepository searchRepository = Mockito.mock(SearchRepository.class); + ClientsRepository clientRepository = Mockito.mock(ClientsRepository.class); + EventsRepository eventsRepository = Mockito.mock(EventsRepository.class); + searchService = Mockito.spy(new SearchService(searchRepository)); + clientService = Mockito.spy(new ClientService(clientRepository)); + eventService = Mockito.spy( + new EventService(eventsRepository, clientService, taskGenerator, planRepository, exportEventDataMapper)); - @Before - public void setUp() { - SearchRepository searchRepository = Mockito.mock(SearchRepository.class); - ClientsRepository clientRepository = Mockito.mock(ClientsRepository.class); - EventsRepository eventsRepository = Mockito.mock(EventsRepository.class); + } - searchService = Mockito.spy(new SearchService(searchRepository)); - clientService = Mockito.spy(new ClientService(clientRepository)); - eventService = Mockito.spy( - new EventService(eventsRepository, clientService, taskGenerator, planRepository, exportEventDataMapper)); + @Test + public void testInstantanceCreatesCorrectly() { + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + Assert.assertNotNull(searchResource); - } + } - @Test - public void testInstantanceCreatesCorrectly() { - SearchResource searchResource = new SearchResource(searchService, clientService, eventService); - Assert.assertNotNull(searchResource); + @Test + public void testIntersectionMethodReturnsCorrectResult() { + Client clientA = Mockito.mock(Client.class); + List listA = Arrays.asList(new Client[]{clientA}); + List result = SearchHelper.intersection(null, listA); - } + Assert.assertNotNull(result); + Assert.assertEquals(listA, result); - @Test - public void testIntersectionMethodReturnsCorrectResult() { - Client clientA = Mockito.mock(Client.class); - List listA = Arrays.asList(new Client[] { clientA }); - List result = SearchHelper.intersection(null, listA); + } - Assert.assertNotNull(result); - Assert.assertEquals(listA, result); + @Test + public void shouldSearchClientWithGetRequest() throws ParseException { + mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addParameter("ff", "ona"); + mockHttpServletRequest.addParameter("phone_number", phoneNumber); + mockHttpServletRequest.addParameter("alt_phone_number", phoneNumber); + mockHttpServletRequest.addParameter("alt_name", firstName); + mockHttpServletRequest.addParameter("attribute", "next_contact_date:2022-06-15"); + mockHttpServletRequest.addParameter("dob", String.valueOf(birthDate)); + mockHttpServletRequest.addParameter("identifier", "fsdf" + ":" + "sfdf"); + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + List clients = searchResource.search(mockHttpServletRequest); + Assert.assertNotNull(clients); + } - } + @Test + public void shouldSearchClientWithPostRequest() throws ParseException { + String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + + "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + + "\"attribute\":\"next_contact_date:2022-06-15\"}"; + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + List clients = searchResource.searchByPost(jsonRequestString); + Assert.assertNotNull(clients); - @Test - public void shouldSearchClientWithGetRequest() throws ParseException { - mockHttpServletRequest = new MockHttpServletRequest(); - mockHttpServletRequest.addParameter("ff", "ona"); - mockHttpServletRequest.addParameter("phone_number", phoneNumber); - mockHttpServletRequest.addParameter("alt_phone_number", phoneNumber); - mockHttpServletRequest.addParameter("alt_name", firstName); - mockHttpServletRequest.addParameter("attribute", "next_contact_date:2022-06-15"); - mockHttpServletRequest.addParameter("dob", String.valueOf(birthDate)); - mockHttpServletRequest.addParameter("identifier", "fsdf"+":"+ "sfdf"); - SearchResource searchResource=new SearchResource(searchService,clientService,eventService); - List clients = searchResource.search(mockHttpServletRequest); - Assert.assertNotNull(clients); - } - - @Test - public void shouldSearchClientWithPostRequest() throws ParseException { - String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + - "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + - "\"attribute\":\"next_contact_date:2022-06-15\"}"; - SearchResource searchResource=new SearchResource(searchService,clientService,eventService); - List clients = searchResource.searchByPost(jsonRequestString); - Assert.assertNotNull(clients); - - } + } } diff --git a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java index 523c6538a..21d0b3348 100644 --- a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java +++ b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java @@ -15,363 +15,363 @@ public class SearchHelperTest { - @Test - public void testCreateClientListIfEmptyCreatesListOnNull() { + @Test + public void testCreateClientListIfEmptyCreatesListOnNull() { - List list = SearchHelper.createClientListIfEmpty(null); - Assert.assertNotNull(list); - } + List list = SearchHelper.createClientListIfEmpty(null); + Assert.assertNotNull(list); + } - @Test - public void testCreateClientListIfEmptyDoesNotModifyParameterList() { - Client client = new Client("dummy-base-entity-id"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + @Test + public void testCreateClientListIfEmptyDoesNotModifyParameterList() { + Client client = new Client("dummy-base-entity-id"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - List myClientList = Arrays.asList(new Client[] { client }); + List myClientList = Arrays.asList(new Client[]{client}); - List list = SearchHelper.createClientListIfEmpty(myClientList); + List list = SearchHelper.createClientListIfEmpty(myClientList); - Assert.assertNotNull(list); - org.springframework.util.Assert.notEmpty(list); - Assert.assertEquals("dummy-base-entity-id", list.get(0).getBaseEntityId()); - Assert.assertEquals("Johnny", list.get(0).getFirstName()); - Assert.assertEquals("Test", list.get(0).getLastName()); - Assert.assertEquals("MALE", list.get(0).getGender()); - } + Assert.assertNotNull(list); + org.springframework.util.Assert.notEmpty(list); + Assert.assertEquals("dummy-base-entity-id", list.get(0).getBaseEntityId()); + Assert.assertEquals("Johnny", list.get(0).getFirstName()); + Assert.assertEquals("Test", list.get(0).getLastName()); + Assert.assertEquals("MALE", list.get(0).getGender()); + } - @Test - public void testGetContactPhoneNumberParamReturnsCorrectValueForParam() { + @Test + public void testGetContactPhoneNumberParamReturnsCorrectValueForParam() { - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; - MockHttpServletRequest req = new MockHttpServletRequest(); - req.addParameter(MOTHER_GUARDIAN_PHONE_NUMBER, "+254738388383"); - req.addParameter(CONTACT_PHONE_NUMBER, "+2547112233445"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.addParameter(MOTHER_GUARDIAN_PHONE_NUMBER, "+254738388383"); + req.addParameter(CONTACT_PHONE_NUMBER, "+2547112233445"); - String motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); + String motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); - Assert.assertNotNull(motherGuardianNum); - Assert.assertEquals("+254738388383", motherGuardianNum); + Assert.assertNotNull(motherGuardianNum); + Assert.assertEquals("+254738388383", motherGuardianNum); - req.removeParameter(MOTHER_GUARDIAN_PHONE_NUMBER); - motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); + req.removeParameter(MOTHER_GUARDIAN_PHONE_NUMBER); + motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); - Assert.assertNotNull(motherGuardianNum); - Assert.assertEquals("+2547112233445", motherGuardianNum); - } + Assert.assertNotNull(motherGuardianNum); + Assert.assertEquals("+2547112233445", motherGuardianNum); + } - @Test - public void testIntersectionReturnsEmptyListIfBothListsEmptyOrNull() { + @Test + public void testIntersectionReturnsEmptyListIfBothListsEmptyOrNull() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - List list2 = new ArrayList<>(); + List list2 = new ArrayList<>(); - List resultList = SearchHelper.intersection(list, list2); + List resultList = SearchHelper.intersection(list, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(0, resultList.size()); + Assert.assertNotNull(resultList); + Assert.assertEquals(0, resultList.size()); - resultList = SearchHelper.intersection(new ArrayList(), new ArrayList()); + resultList = SearchHelper.intersection(new ArrayList(), new ArrayList()); - Assert.assertNotNull(resultList); - Assert.assertEquals(0, resultList.size()); + Assert.assertNotNull(resultList); + Assert.assertEquals(0, resultList.size()); - } + } - @Test - public void testIntersectionReturnsClientListAIfClientBListIsNullOrEmpty() { + @Test + public void testIntersectionReturnsClientListAIfClientBListIsNullOrEmpty() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client = new Client("dummy-base-entity-id_1"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + Client client = new Client("dummy-base-entity-id_1"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - Client client2 = new Client("dummy-base-entity-id_2"); - client2.setFirstName("Jane"); - client2.setLastName("Test"); - client2.setGender("FEMALE"); + Client client2 = new Client("dummy-base-entity-id_2"); + client2.setFirstName("Jane"); + client2.setLastName("Test"); + client2.setGender("FEMALE"); - list.add(client); - list.add(client2); + list.add(client); + list.add(client2); - List resultList = SearchHelper.intersection(list, null); + List resultList = SearchHelper.intersection(list, null); - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - resultList = SearchHelper.intersection(list, new ArrayList()); + resultList = SearchHelper.intersection(list, new ArrayList()); - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - } + } - @Test - public void testIntersectionReturnsClientListBIfClientAListIsNullOrEmpty() { + @Test + public void testIntersectionReturnsClientListBIfClientAListIsNullOrEmpty() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client3 = new Client("dummy-base-entity-id_3"); - client3.setFirstName("James"); - client3.setLastName("Dean"); - client3.setGender("MALE"); + Client client3 = new Client("dummy-base-entity-id_3"); + client3.setFirstName("James"); + client3.setLastName("Dean"); + client3.setGender("MALE"); - Client client4 = new Client("dummy-base-entity-id_1"); - client4.setFirstName("Johnny"); - client4.setLastName("Test"); - client4.setGender("MALE"); + Client client4 = new Client("dummy-base-entity-id_1"); + client4.setFirstName("Johnny"); + client4.setLastName("Test"); + client4.setGender("MALE"); - Client client5 = new Client("dummy-base-entity-id_2"); - client5.setFirstName("Jane"); - client5.setLastName("Test"); - client5.setGender("FEMALE"); + Client client5 = new Client("dummy-base-entity-id_2"); + client5.setFirstName("Jane"); + client5.setLastName("Test"); + client5.setGender("FEMALE"); - List list2 = new ArrayList<>(); + List list2 = new ArrayList<>(); - list2.add(client3); - list2.add(client4); - list2.add(client5); + list2.add(client3); + list2.add(client4); + list2.add(client5); - List resultList = SearchHelper.intersection(list, list2); + List resultList = SearchHelper.intersection(list, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(3, resultList.size()); - Assert.assertEquals("James", resultList.get(0).getFirstName()); - Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); - Assert.assertEquals("Jane", resultList.get(2).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(3, resultList.size()); + Assert.assertEquals("James", resultList.get(0).getFirstName()); + Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); + Assert.assertEquals("Jane", resultList.get(2).getFirstName()); - resultList = SearchHelper.intersection(null, list2); + resultList = SearchHelper.intersection(null, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(3, resultList.size()); - Assert.assertEquals("James", resultList.get(0).getFirstName()); - Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); - Assert.assertEquals("Jane", resultList.get(2).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(3, resultList.size()); + Assert.assertEquals("James", resultList.get(0).getFirstName()); + Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); + Assert.assertEquals("Jane", resultList.get(2).getFirstName()); - } + } - @Test - public void testIntersectionReturnsAConjunctionOfTwoClientLists() { + @Test + public void testIntersectionReturnsAConjunctionOfTwoClientLists() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client = new Client("dummy-base-entity-id_1"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + Client client = new Client("dummy-base-entity-id_1"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - Client client2 = new Client("dummy-base-entity-id_2"); - client2.setFirstName("Jane"); - client2.setLastName("Test"); - client2.setGender("FEMALE"); - - list.add(client); - list.add(client2); - - Client client3 = new Client("dummy-base-entity-id_3"); - client3.setFirstName("James"); - client3.setLastName("Dean"); - client3.setGender("MALE"); - - Client client4 = new Client("dummy-base-entity-id_1"); - client4.setFirstName("Johnny"); - client4.setLastName("Test"); - client4.setGender("MALE"); - - Client client5 = new Client("dummy-base-entity-id_2"); - client5.setFirstName("Jane"); - client5.setLastName("Test"); - client5.setGender("FEMALE"); - - List list2 = new ArrayList<>(); - - list2.add(client3); - list2.add(client4); - list2.add(client5); - - List resultList = SearchHelper.intersection(list, list2); - - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - - } - - @Test - public void childSearchParamProcessorShouldHaveCorrectIdentifierWhenCreatingBean() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("20"); - Mockito.when(httpServletRequest.getParameter("opensrp_id")).thenReturn("2093980"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); - String result = searchEntityWrapper.getClientSearchBean().getIdentifiers().get("opensrp_id"); - Assert.assertEquals("2093980", result); - } - - @Test - public void testProcessSearchResult() { - final String mother = "mother"; - - Client motherClient = new Client("dummy-mother-base-entity-id"); - motherClient.setFirstName("Jane"); - motherClient.setLastName("Doe"); - motherClient.setGender("FEMALE"); - motherClient.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); - List motherList = new ArrayList<>(); - motherList.add(motherClient); - - List list = new ArrayList<>(); - list.add("dummy-mother-base-entity-id"); - - Map> relationships = new HashMap<>(); - relationships.put(mother, list); - - Client child = new Client("dummy-mother-base-entity-id"); - child.setFirstName("John"); - child.setLastName("Doe"); - child.setGender("Male"); - child.setRelationships(relationships); - child.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); - - List childList = new ArrayList<>(); - childList.add(child); - - List childMothers = SearchHelper.processSearchResult(childList, motherList, mother); - Assert.assertEquals(1, childMothers.size()); - Assert.assertEquals("John Doe", childMothers.get(0).getChild().fullName()); - } - - @Test - public void testMotherSearchParamProcessorForHttpServletRequest() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("0"); - Mockito.when(httpServletRequest.getParameter("mother_first_name")).thenReturn("Jane"); - Mockito.when(httpServletRequest.getParameter("mother_last_name")).thenReturn("Doe"); - Mockito.when(httpServletRequest.getParameter("mother_nrc_number")).thenReturn("2093980"); - Mockito.when(httpServletRequest.getParameter("NRC_Number")).thenReturn("20939801123"); - Mockito.when(httpServletRequest.getParameter("mother_compass_relationship_id")).thenReturn("dab102f71bd"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(httpServletRequest); - Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(2, result.size()); - Assert.assertTrue( result.containsKey("NRC_Number")); - Assert.assertTrue( result.containsKey("Compass_Relationship_ID")); - Assert.assertEquals("2093980", result.get("NRC_Number")); - } - - @Test - public void testMotherSearchParamProcessorForJSONObject() throws ParseException { - JSONObject jsonObject = Mockito.mock(JSONObject.class); - Mockito.when(jsonObject.optString("limit")).thenReturn("0"); - Mockito.when(jsonObject.optString("mother_first_name")).thenReturn("Jane"); - Mockito.when(jsonObject.optString("mother_last_name")).thenReturn("Doe"); - Mockito.when(jsonObject.optString("mother_nrc_number")).thenReturn("2093980"); - Mockito.when(jsonObject.optString("NRC_Number")).thenReturn("20939801123"); - Mockito.when(jsonObject.optString("mother_compass_relationship_id")).thenReturn("dab102f71bd"); - Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); - SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(jsonObject); - Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(2, result.size()); - Assert.assertTrue( result.containsKey("NRC_Number")); - Assert.assertTrue( result.containsKey("Compass_Relationship_ID")); - Assert.assertEquals("2093980", result.get("NRC_Number")); - } - - @Test - public void testChildSearchParamProcessorForJSONObject() throws ParseException { - JSONObject jsonObject = Mockito.mock(JSONObject.class); - Mockito.when(jsonObject.optString("limit")).thenReturn("50"); - Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); - Mockito.when(jsonObject.optString(SearchHelper.BIRTH_DATE)).thenReturn(""); - Mockito.when(jsonObject.optString(SearchHelper.ZEIR_ID)).thenReturn("1234"); - Mockito.when(jsonObject.optString(SearchHelper.OPENSRP_ID)).thenReturn("4567"); - Mockito.when(jsonObject.optString(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); - Mockito.when(jsonObject.optString(SearchHelper.INACTIVE)).thenReturn("false"); - Mockito.when(jsonObject.optString(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); - Mockito.when(jsonObject.optString(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(jsonObject); - - Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(3, attributes.size()); - - Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); - Assert.assertEquals(4, identifiers.size()); - - Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); - Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key - Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); - - Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); - Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); - Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); - - Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); - Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); - } - - @Test - public void testChildSearchParamProcessorForHttpServletRequest() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("50"); - Mockito.when(httpServletRequest.getParameter("lastEdited")).thenReturn(""); - Mockito.when(httpServletRequest.getParameter(SearchHelper.BIRTH_DATE)).thenReturn(""); - Mockito.when(httpServletRequest.getParameter(SearchHelper.ZEIR_ID)).thenReturn("1234"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.OPENSRP_ID)).thenReturn("4567"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.INACTIVE)).thenReturn("false"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); - - Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(3, attributes.size()); - - Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); - Assert.assertEquals(4, identifiers.size()); - - Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); - Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key - Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); - - Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); - Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); - Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); - - Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); - Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); - } - - @Test - public void testSetCoreFiltersForJSONObjectWithIntegerLimitReturnsValue(){ - JSONObject jsonObject = new JSONObject(); - jsonObject.put("limit", 50); - try { - int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); - Assert.assertEquals(50,result); - } catch (ParseException e) { - e.printStackTrace(); - } - } - - @Test - public void testSetCoreFiltersForJSONObjectWithStringLimitReturnsValue(){ - JSONObject jsonObject = new JSONObject(); - jsonObject.put("limit", "50"); - try { - int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); - Assert.assertEquals(50,result); - } catch (ParseException e) { - e.printStackTrace(); - } - } + Client client2 = new Client("dummy-base-entity-id_2"); + client2.setFirstName("Jane"); + client2.setLastName("Test"); + client2.setGender("FEMALE"); + + list.add(client); + list.add(client2); + + Client client3 = new Client("dummy-base-entity-id_3"); + client3.setFirstName("James"); + client3.setLastName("Dean"); + client3.setGender("MALE"); + + Client client4 = new Client("dummy-base-entity-id_1"); + client4.setFirstName("Johnny"); + client4.setLastName("Test"); + client4.setGender("MALE"); + + Client client5 = new Client("dummy-base-entity-id_2"); + client5.setFirstName("Jane"); + client5.setLastName("Test"); + client5.setGender("FEMALE"); + + List list2 = new ArrayList<>(); + + list2.add(client3); + list2.add(client4); + list2.add(client5); + + List resultList = SearchHelper.intersection(list, list2); + + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + + } + + @Test + public void childSearchParamProcessorShouldHaveCorrectIdentifierWhenCreatingBean() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("20"); + Mockito.when(httpServletRequest.getParameter("opensrp_id")).thenReturn("2093980"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); + String result = searchEntityWrapper.getClientSearchBean().getIdentifiers().get("opensrp_id"); + Assert.assertEquals("2093980", result); + } + + @Test + public void testProcessSearchResult() { + final String mother = "mother"; + + Client motherClient = new Client("dummy-mother-base-entity-id"); + motherClient.setFirstName("Jane"); + motherClient.setLastName("Doe"); + motherClient.setGender("FEMALE"); + motherClient.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); + List motherList = new ArrayList<>(); + motherList.add(motherClient); + + List list = new ArrayList<>(); + list.add("dummy-mother-base-entity-id"); + + Map> relationships = new HashMap<>(); + relationships.put(mother, list); + + Client child = new Client("dummy-mother-base-entity-id"); + child.setFirstName("John"); + child.setLastName("Doe"); + child.setGender("Male"); + child.setRelationships(relationships); + child.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); + + List childList = new ArrayList<>(); + childList.add(child); + + List childMothers = SearchHelper.processSearchResult(childList, motherList, mother); + Assert.assertEquals(1, childMothers.size()); + Assert.assertEquals("John Doe", childMothers.get(0).getChild().fullName()); + } + + @Test + public void testMotherSearchParamProcessorForHttpServletRequest() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("0"); + Mockito.when(httpServletRequest.getParameter("mother_first_name")).thenReturn("Jane"); + Mockito.when(httpServletRequest.getParameter("mother_last_name")).thenReturn("Doe"); + Mockito.when(httpServletRequest.getParameter("mother_nrc_number")).thenReturn("2093980"); + Mockito.when(httpServletRequest.getParameter("NRC_Number")).thenReturn("20939801123"); + Mockito.when(httpServletRequest.getParameter("mother_compass_relationship_id")).thenReturn("dab102f71bd"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(httpServletRequest); + Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(2, result.size()); + Assert.assertTrue(result.containsKey("NRC_Number")); + Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); + Assert.assertEquals("2093980", result.get("NRC_Number")); + } + + @Test + public void testMotherSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("0"); + Mockito.when(jsonObject.optString("mother_first_name")).thenReturn("Jane"); + Mockito.when(jsonObject.optString("mother_last_name")).thenReturn("Doe"); + Mockito.when(jsonObject.optString("mother_nrc_number")).thenReturn("2093980"); + Mockito.when(jsonObject.optString("NRC_Number")).thenReturn("20939801123"); + Mockito.when(jsonObject.optString("mother_compass_relationship_id")).thenReturn("dab102f71bd"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(jsonObject); + Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(2, result.size()); + Assert.assertTrue(result.containsKey("NRC_Number")); + Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); + Assert.assertEquals("2093980", result.get("NRC_Number")); + } + + @Test + public void testChildSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("50"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(jsonObject.optString(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(jsonObject.optString(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(jsonObject.optString(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(jsonObject.optString(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(jsonObject.optString(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(jsonObject); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testChildSearchParamProcessorForHttpServletRequest() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("50"); + Mockito.when(httpServletRequest.getParameter("lastEdited")).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testSetCoreFiltersForJSONObjectWithIntegerLimitReturnsValue() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", 50); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50, result); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testSetCoreFiltersForJSONObjectWithStringLimitReturnsValue() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", "50"); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50, result); + } catch (ParseException e) { + e.printStackTrace(); + } + } } From db87055d1729050ad6411c758f853e153185e3ca Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 23 Nov 2022 09:46:44 +0300 Subject: [PATCH 04/27] rename searchByPath methods --- src/main/java/org/opensrp/web/rest/SearchResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 082dd24b9..d8af41a7b 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -174,7 +174,7 @@ public List searchByPost(@RequestBody String jsonRequestBody) throws Par } @RequestMapping(method = RequestMethod.GET, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - private List searchPathBy(HttpServletRequest request) throws ParseException { + private List searchPathByGet(HttpServletRequest request) throws ParseException { String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); @@ -184,7 +184,7 @@ private List searchPathBy(HttpServletRequest request) throws ParseE } @RequestMapping(method = RequestMethod.POST, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - private List searchPathBy(@RequestBody String jsonRequestBody) throws ParseException { + private List searchPathByPost(@RequestBody String jsonRequestBody) throws ParseException { JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); From 87c1806b5286ba69f106dba131bc6d9abfde2e0b Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 23 Nov 2022 09:56:50 +0300 Subject: [PATCH 05/27] fix codacy issues --- src/test/java/org/opensrp/web/rest/SearchResourceTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index fc1521ba3..42fd9d277 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -14,7 +14,6 @@ import org.opensrp.repository.SearchRepository; import org.opensrp.service.ClientService; import org.opensrp.service.EventService; -import org.opensrp.service.ExportEventDataMapper; import org.opensrp.service.SearchService; import org.opensrp.service.TaskGenerator; import org.opensrp.web.rest.it.TestWebContextLoader; @@ -43,8 +42,6 @@ public class SearchResourceTest { private EventService eventService; - private ExportEventDataMapper exportEventDataMapper; - private TaskGenerator taskGenerator; private PlanRepository planRepository; From 6e72c94693f9630d2fa7b3957472c952466c7d76 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 23 Nov 2022 10:18:55 +0300 Subject: [PATCH 06/27] revert deleted exportEventDataMapper --- src/test/java/org/opensrp/web/rest/SearchResourceTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index 42fd9d277..fc1521ba3 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -14,6 +14,7 @@ import org.opensrp.repository.SearchRepository; import org.opensrp.service.ClientService; import org.opensrp.service.EventService; +import org.opensrp.service.ExportEventDataMapper; import org.opensrp.service.SearchService; import org.opensrp.service.TaskGenerator; import org.opensrp.web.rest.it.TestWebContextLoader; @@ -42,6 +43,8 @@ public class SearchResourceTest { private EventService eventService; + private ExportEventDataMapper exportEventDataMapper; + private TaskGenerator taskGenerator; private PlanRepository planRepository; From c98a3d175d0b3eed83024781fa5dd4c48a901e34 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Thu, 22 Dec 2022 10:43:56 +0300 Subject: [PATCH 07/27] use SearchService#searchGlobalClient instead of searchClient method --- .../java/org/opensrp/web/rest/SearchResource.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index d8af41a7b..7e124dfab 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -174,7 +174,7 @@ public List searchByPost(@RequestBody String jsonRequestBody) throws Par } @RequestMapping(method = RequestMethod.GET, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - private List searchPathByGet(HttpServletRequest request) throws ParseException { + public List searchPathByGet(HttpServletRequest request) throws ParseException { String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); @@ -184,12 +184,13 @@ private List searchPathByGet(HttpServletRequest request) throws Par } @RequestMapping(method = RequestMethod.POST, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - private List searchPathByPost(@RequestBody String jsonRequestBody) throws ParseException { + public List searchPathByPost(@RequestBody String jsonRequestBody) throws ParseException { JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); + + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); @@ -204,7 +205,7 @@ private List searchAndProcess(SearchEntityWrapper childSearchEntity List children = new ArrayList(); if (childSearchEntity.isValid()) { searchBean = childSearchEntity.getClientSearchBean(); - children = searchService.searchClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), + children = searchService.searchGlobalClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), searchBean.getLastName(), childSearchEntity.getLimit()); } @@ -215,7 +216,7 @@ private List searchAndProcess(SearchEntityWrapper childSearchEntity if (motherSearchEntity.isValid()) { motherSearchBean = motherSearchEntity.getClientSearchBean(); - mothers = searchService.searchClient(motherSearchBean, motherSearchBean.getFirstName(), + mothers = searchService.searchGlobalClient(motherSearchBean, motherSearchBean.getFirstName(), motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); } From 0327bc4d47153c5c7c5495e3507b9c0a60348e99 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Thu, 22 Dec 2022 12:52:48 +0300 Subject: [PATCH 08/27] get json string values as null instead of empty string --- .../java/org/opensrp/web/rest/RestUtils.java | 4 +++ .../org/opensrp/web/utils/SearchHelper.java | 28 +++++++++---------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 1325d4828..afe564077 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -43,6 +43,10 @@ public static String getStringFilter(String filter, HttpServletRequest req) { return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter); } + public static String getStringFilter(String filter, JSONObject jsonObject) { + return StringUtils.isBlank(jsonObject.optString(filter)) ? null : jsonObject.optString(filter); + } + @SuppressWarnings({"unchecked", "rawtypes"}) public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) { String filterVal = getStringFilter(filter, req); diff --git a/src/main/java/org/opensrp/web/utils/SearchHelper.java b/src/main/java/org/opensrp/web/utils/SearchHelper.java index d34930572..7d6006f9e 100644 --- a/src/main/java/org/opensrp/web/utils/SearchHelper.java +++ b/src/main/java/org/opensrp/web/utils/SearchHelper.java @@ -126,10 +126,10 @@ public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObjec searchBean.setLastEditTo(lastEdit[1]); } - searchBean.setFirstName(jsonObject.optString(FIRST_NAME)); - searchBean.setMiddleName(jsonObject.optString(MIDDLE_NAME)); - searchBean.setLastName(jsonObject.optString(LAST_NAME)); - searchBean.setGender(jsonObject.optString(GENDER)); + searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, jsonObject)); + searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, jsonObject)); + searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, jsonObject)); + searchBean.setGender(RestUtils.getStringFilter(GENDER, jsonObject)); DateTime[] birthdate = RestUtils .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html @@ -142,12 +142,12 @@ public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObjec } Map commonSearchParams = new HashMap<>(); - commonSearchParams.put(ZEIR_ID, jsonObject.optString(ZEIR_ID)); - commonSearchParams.put(OPENSRP_ID, jsonObject.optString(OPENSRP_ID)); - commonSearchParams.put(SIM_PRINT_GUID, jsonObject.optString(SIM_PRINT_GUID)); - commonSearchParams.put(INACTIVE, jsonObject.optString(INACTIVE)); - commonSearchParams.put(LOST_TO_FOLLOW_UP, jsonObject.optString(LOST_TO_FOLLOW_UP)); - commonSearchParams.put(NFC_CARD_IDENTIFIER, jsonObject.optString(NFC_CARD_IDENTIFIER)); + commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, jsonObject)); + commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, jsonObject)); + commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, jsonObject)); + commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, jsonObject)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, jsonObject)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, jsonObject)); setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); @@ -162,11 +162,11 @@ public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObje Integer limit = setCoreFilters(jsonObject, motherSearchBean); - String motherGuardianNrc = jsonObject.optString(MOTHER_GUARDIAN_NRC_NUMBER); - String compassRelationshipId = jsonObject.optString(MOTHER_COMPASS_RELATIONSHIP_ID); + String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, jsonObject); + String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, jsonObject); - motherSearchBean.setFirstName(jsonObject.optString(MOTHER_GUARDIAN_FIRST_NAME)); - motherSearchBean.setLastName(jsonObject.optString(MOTHER_GUARDIAN_LAST_NAME)); + motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, jsonObject)); + motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, jsonObject)); setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); From 5739e7556c64db30405c7d9717186f93939c13eb Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 23 Dec 2022 11:28:45 +0300 Subject: [PATCH 09/27] extract out duplicates in old search method --- .../org/opensrp/web/rest/SearchResource.java | 194 +++++++++--------- 1 file changed, 100 insertions(+), 94 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 7e124dfab..2b670c644 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -1,6 +1,8 @@ package org.opensrp.web.rest; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; @@ -72,105 +74,15 @@ public SearchResource(SearchService searchService, ClientService clientService, */ @Override public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params - String firstName = getStringFilter(FIRST_NAME, request); - String middleName = getStringFilter(MIDDLE_NAME, request); - String lastName = getStringFilter(LAST_NAME, request); - Optional phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); - Optional altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); - Optional alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); - ClientSearchBean searchBean = new ClientSearchBean(); - searchBean.setNameLike(getStringFilter(NAME, request)); - - searchBean.setGender(getStringFilter(GENDER, request)); - DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, - request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - Map attributeMap = new HashMap<>(); - String attributes = getStringFilter(ATTRIBUTE, request); - if (!StringUtils.isBlank(attributes)) { - String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; - String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; - attributeMap.put(attributeType, attributeValue); - } - phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); - altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); - alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); - searchBean.setAttributes(attributeMap); - - Map identifierMap = null; - String identifiers = getStringFilter(IDENTIFIER, request); - if (!StringUtils.isBlank(identifiers)) { - String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; - String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; - - identifierMap = new HashMap<>(); - identifierMap.put(identifierType, identifierValue); - } - - searchBean.setIdentifiers(identifierMap); - return searchService.searchClient(searchBean, firstName, middleName, lastName, null); + Pair> result = extractNamesAndCreateClientSearchBean(request); + return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); } @RequestMapping(method = RequestMethod.POST, value = "/search", produces = {MediaType.APPLICATION_JSON_VALUE}) public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params - JSONObject jsonObject = new JSONObject(jsonRequestBody); - String firstName = jsonObject.optString(FIRST_NAME); - String middleName = jsonObject.optString(MIDDLE_NAME); - String lastName = jsonObject.optString(LAST_NAME); - Optional phoneNumber = Optional.ofNullable(jsonObject.optString(PHONE_NUMBER)); - Optional altPhoneNumber = Optional.ofNullable(jsonObject.optString(ALT_PHONE_NUMBER)); - Optional alternateName = Optional.ofNullable(jsonObject.optString(ALT_NAME)); - ClientSearchBean searchBean = new ClientSearchBean(); - searchBean.setNameLike(jsonObject.optString(NAME)); - - searchBean.setGender(jsonObject.optString(GENDER)); - DateTime[] birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - Map attributeMap = new HashMap<>(); - String attributes = jsonObject.optString(ATTRIBUTE); - if (!StringUtils.isBlank(attributes)) { - String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; - String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; - attributeMap.put(attributeType, attributeValue); - } - phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); - altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); - alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); - searchBean.setAttributes(attributeMap); - - Map identifierMap = null; - String identifiers = jsonObject.optString(IDENTIFIER); - if (!StringUtils.isBlank(identifiers)) { - String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; - String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; - - identifierMap = new HashMap(); - identifierMap.put(identifierType, identifierValue); - } + Pair> result = extractNamesAndCreateClientSearchBean(jsonRequestBody); + return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); - searchBean.setIdentifiers(identifierMap); - return searchService.searchClient(searchBean, firstName, middleName, lastName, null); } @RequestMapping(method = RequestMethod.GET, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) @@ -290,6 +202,100 @@ public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuar return clientBaseEntityIds; } + public Pair> extractNamesAndCreateClientSearchBean(Object object) throws ParseException { + + String firstName = null; + String middleName = null; + String lastName = null; + String name = null; + String gender = null; + String attributes = null; + String identifiers = null; + Optional phoneNumber, altPhoneNumber, alternateName; + DateTime[] birthdate, lastEdit; + + ClientSearchBean searchBean = new ClientSearchBean(); + + if(object instanceof HttpServletRequest){ + HttpServletRequest request = (HttpServletRequest) object; + firstName = getStringFilter(FIRST_NAME, request); + middleName = getStringFilter(MIDDLE_NAME, request); + lastName = getStringFilter(LAST_NAME, request); + + phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); + altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); + alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); + + name = getStringFilter(NAME, request); + gender = getStringFilter(GENDER, request); + + birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + attributes = getStringFilter(ATTRIBUTE, request); + identifiers = getStringFilter(IDENTIFIER, request); + + } else { + JSONObject jsonObject = new JSONObject((String) object); + + firstName = RestUtils.getStringFilter(FIRST_NAME, jsonObject); + middleName = RestUtils.getStringFilter(MIDDLE_NAME, jsonObject); + lastName = RestUtils.getStringFilter(LAST_NAME, jsonObject); + + phoneNumber = Optional.ofNullable(RestUtils.getStringFilter(PHONE_NUMBER, jsonObject)); + altPhoneNumber = Optional.ofNullable(RestUtils.getStringFilter(ALT_PHONE_NUMBER, jsonObject)); + alternateName = Optional.ofNullable(RestUtils.getStringFilter(ALT_NAME, jsonObject)); + + + name = RestUtils.getStringFilter(NAME, jsonObject); + gender = RestUtils.getStringFilter(GENDER, jsonObject); + + birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + attributes = RestUtils.getStringFilter(ATTRIBUTE, jsonObject); + identifiers = RestUtils.getStringFilter(IDENTIFIER, jsonObject); + + } + + searchBean.setNameLike(name); + searchBean.setGender(gender); + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + Map attributeMap = new HashMap<>(); + + + if (!StringUtils.isBlank(attributes)) { + String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; + String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; + attributeMap.put(attributeType, attributeValue); + } + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); + altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); + alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + searchBean.setAttributes(attributeMap); + + Map identifierMap = new HashMap<>(); + if (!StringUtils.isBlank(identifiers)) { + String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; + String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; + identifierMap.put(identifierType, identifierValue); + } + + + searchBean.setIdentifiers(identifierMap); + + return Pair.of(searchBean, Triple.of(firstName, lastName, middleName)); + } @Override public List filter(String query) { // TODO Auto-generated method stub From 7b80ee693432951a45a6fd13a97f3282d4170d4d Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 23 Dec 2022 12:09:01 +0300 Subject: [PATCH 10/27] Trigger checks From 11d8a0574c60daac85380d06e989395d46099a82 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 9 Jan 2023 10:18:21 +0300 Subject: [PATCH 11/27] update codacy suggestions --- .../org/opensrp/web/rest/SearchResource.java | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 2b670c644..d850b2d8a 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -45,6 +45,7 @@ import static org.opensrp.common.AllConstants.Client.ALT_PHONE_NUMBER; import static org.opensrp.common.AllConstants.Client.BIRTH_DATE; import static org.opensrp.web.rest.RestUtils.getStringFilter; +import static org.opensrp.web.rest.RestUtils.getDateRangeFilter; @Controller @RequestMapping(value = "/rest/search") @@ -204,15 +205,18 @@ public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuar public Pair> extractNamesAndCreateClientSearchBean(Object object) throws ParseException { - String firstName = null; - String middleName = null; - String lastName = null; - String name = null; - String gender = null; - String attributes = null; - String identifiers = null; - Optional phoneNumber, altPhoneNumber, alternateName; - DateTime[] birthdate, lastEdit; + String firstName; + String middleName; + String lastName; + String name; + String gender; + String attributes; + String identifiers; + Optional phoneNumber; + Optional altPhoneNumber; + Optional alternateName; + DateTime[] birthdate; + DateTime[] lastEdit; ClientSearchBean searchBean = new ClientSearchBean(); @@ -229,8 +233,8 @@ public Pair> extractNamesAndCre name = getStringFilter(NAME, request); gender = getStringFilter(GENDER, request); - birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + birthdate = getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a attributes = getStringFilter(ATTRIBUTE, request); identifiers = getStringFilter(IDENTIFIER, request); @@ -238,24 +242,24 @@ public Pair> extractNamesAndCre } else { JSONObject jsonObject = new JSONObject((String) object); - firstName = RestUtils.getStringFilter(FIRST_NAME, jsonObject); - middleName = RestUtils.getStringFilter(MIDDLE_NAME, jsonObject); - lastName = RestUtils.getStringFilter(LAST_NAME, jsonObject); + firstName = getStringFilter(FIRST_NAME, jsonObject); + middleName = getStringFilter(MIDDLE_NAME, jsonObject); + lastName = getStringFilter(LAST_NAME, jsonObject); - phoneNumber = Optional.ofNullable(RestUtils.getStringFilter(PHONE_NUMBER, jsonObject)); - altPhoneNumber = Optional.ofNullable(RestUtils.getStringFilter(ALT_PHONE_NUMBER, jsonObject)); - alternateName = Optional.ofNullable(RestUtils.getStringFilter(ALT_NAME, jsonObject)); + phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, jsonObject)); + altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, jsonObject)); + alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, jsonObject)); - name = RestUtils.getStringFilter(NAME, jsonObject); - gender = RestUtils.getStringFilter(GENDER, jsonObject); + name = getStringFilter(NAME, jsonObject); + gender = getStringFilter(GENDER, jsonObject); - birthdate = RestUtils.getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + birthdate = getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - attributes = RestUtils.getStringFilter(ATTRIBUTE, jsonObject); - identifiers = RestUtils.getStringFilter(IDENTIFIER, jsonObject); + attributes = getStringFilter(ATTRIBUTE, jsonObject); + identifiers = getStringFilter(IDENTIFIER, jsonObject); } From 92098c96db7025e8333a219acbb29a127c255a4a Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 9 Jan 2023 12:31:01 +0300 Subject: [PATCH 12/27] reduce NPath complexity --- .../org/opensrp/web/rest/SearchResource.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index d850b2d8a..227bb4f00 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -277,25 +277,27 @@ public Pair> extractNamesAndCre Map attributeMap = new HashMap<>(); - if (!StringUtils.isBlank(attributes)) { - String attributeType = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[0]; - String attributeValue = StringUtils.isBlank(attributes) ? null : attributes.split(":", -1)[1]; - attributeMap.put(attributeType, attributeValue); + String[] attributeParts = attributes.split(":", -1); + if (attributeParts.length == 2) { + attributeMap.put(attributeParts[0], attributeParts[1]); // put attributeType and attributeValue as key value pair + } } + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + searchBean.setAttributes(attributeMap); Map identifierMap = new HashMap<>(); if (!StringUtils.isBlank(identifiers)) { - String identifierType = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[0]; - String identifierValue = StringUtils.isBlank(identifiers) ? null : identifiers.split(":", -1)[1]; - identifierMap.put(identifierType, identifierValue); + String[] identifierParts = identifiers.split(":", -1); + if (identifierParts.length == 2) { + identifierMap.put(identifierParts[0], identifierParts[1]); // put identifierType and identifierValue key value pair + } } - searchBean.setIdentifiers(identifierMap); return Pair.of(searchBean, Triple.of(firstName, lastName, middleName)); From 451dad727281e709e02e604943a44ddc2260860a Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 9 Jan 2023 21:41:48 +0300 Subject: [PATCH 13/27] deduplicate setCoreFilters --- .../org/opensrp/web/utils/SearchHelper.java | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/opensrp/web/utils/SearchHelper.java b/src/main/java/org/opensrp/web/utils/SearchHelper.java index 7d6006f9e..2a56779a6 100644 --- a/src/main/java/org/opensrp/web/utils/SearchHelper.java +++ b/src/main/java/org/opensrp/web/utils/SearchHelper.java @@ -245,37 +245,36 @@ public static void setIdentifiersAndAttributeToChildSearchBean(Map Date: Thu, 12 Jan 2023 16:09:09 +0300 Subject: [PATCH 14/27] deduplicate setcorefilters --- .../org/opensrp/web/rest/ClientResource.java | 2 +- .../org/opensrp/web/rest/EventResource.java | 10 +++--- .../opensrp/web/rest/LocationResource.java | 4 +-- .../org/opensrp/web/rest/PlanResource.java | 2 +- .../java/org/opensrp/web/rest/RestUtils.java | 31 +++++++++---------- .../org/opensrp/web/rest/TaskResource.java | 2 +- .../java/org/opensrp/web/utils/Utils.java | 11 +++++-- .../java/org/opensrp/web/utils/UtilsTest.java | 6 ++-- 8 files changed, 35 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/ClientResource.java b/src/main/java/org/opensrp/web/rest/ClientResource.java index 2aa4a53a5..1681c2198 100644 --- a/src/main/java/org/opensrp/web/rest/ClientResource.java +++ b/src/main/java/org/opensrp/web/rest/ClientResource.java @@ -432,7 +432,7 @@ public ResponseEntity findIds( @RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> taskIdsPair = clientService.findAllIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, isArchived, - Utils.getDateTimeFromString(fromDate), Utils.getDateTimeFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(taskIdsPair.getLeft()); identifiers.setLastServerVersion(taskIdsPair.getRight()); diff --git a/src/main/java/org/opensrp/web/rest/EventResource.java b/src/main/java/org/opensrp/web/rest/EventResource.java index 9eeb56f1f..1a9be2187 100755 --- a/src/main/java/org/opensrp/web/rest/EventResource.java +++ b/src/main/java/org/opensrp/web/rest/EventResource.java @@ -647,8 +647,8 @@ protected ResponseEntity getAllIdsByEventType( try { Pair, Long> eventIdsPair = eventService.findAllIdsByEventType(eventType, isDeleted, serverVersion, - Constants.DEFAULT_GET_ALL_IDS_LIMIT, Utils.getDateTimeFromString(fromDate), - Utils.getDateTimeFromString(toDate)); + Constants.DEFAULT_GET_ALL_IDS_LIMIT, Utils.getDateFromString(fromDate), + Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(eventIdsPair.getLeft()); identifiers.setLastServerVersion(eventIdsPair.getRight()); @@ -682,8 +682,8 @@ public ResponseEntity exportEventData(@RequestParam List findIds( @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> structureIdsPair = locationService.findAllStructureIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateTimeFromString(fromDate), Utils.getDateTimeFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(structureIdsPair.getLeft()); identifiers.setLastServerVersion(structureIdsPair.getRight()); @@ -525,7 +525,7 @@ public ResponseEntity findLocationIds( @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> locationIdsPair = locationService.findAllLocationIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateTimeFromString(fromDate), Utils.getDateTimeFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(locationIdsPair.getLeft()); identifiers.setLastServerVersion(locationIdsPair.getRight()); diff --git a/src/main/java/org/opensrp/web/rest/PlanResource.java b/src/main/java/org/opensrp/web/rest/PlanResource.java index 5f340906d..1d5f0dd15 100644 --- a/src/main/java/org/opensrp/web/rest/PlanResource.java +++ b/src/main/java/org/opensrp/web/rest/PlanResource.java @@ -324,7 +324,7 @@ public ResponseEntity findIds(@RequestParam(value = SERVER_VERSIOIN, @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> planIdsPair = planService.findAllIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, isDeleted, - Utils.getDateTimeFromString(fromDate), Utils.getDateTimeFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(planIdsPair.getLeft()); identifiers.setLastServerVersion(planIdsPair.getRight()); diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index afe564077..787f4962f 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -12,6 +12,7 @@ import org.opensrp.domain.Multimedia; import org.opensrp.service.multimedia.MultimediaFileManager; import org.opensrp.service.multimedia.S3MultimediaFileManager; +import org.opensrp.web.utils.Utils; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; @@ -71,29 +72,25 @@ public static DateTime getDateFilter(String filter, HttpServletRequest req) thro return strval == null ? null : new DateTime(strval); } - public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException { - String strval = getStringFilter(filter, req); - if (strval == null) { - return null; - } - if (!strval.contains(":")) { - return new DateTime[]{new DateTime(strval), new DateTime(strval)}; + public static DateTime[] getDateRangeFilter(String filter, Object object) throws ParseException { + String strval; + + if(object instanceof HttpServletRequest){ + HttpServletRequest req = (HttpServletRequest) object; + strval = getStringFilter(filter, req); + } else { + JSONObject jsonObject = (JSONObject) object; + strval = getStringFilter(filter, jsonObject); } - DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1)); - return new DateTime[]{d1, d2}; - } - public static DateTime[] getDateRangeFilter(String filter, JSONObject jsonObject) throws ParseException { - String strval = jsonObject.optString(filter); - if (strval.equals("")) { + if (strval == null) { return null; } if (!strval.contains(":")) { - return new DateTime[]{new DateTime(strval), new DateTime(strval)}; + return new DateTime[]{Utils.getDateTimeFromString(strval),Utils.getDateTimeFromString(strval)}; } - DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1)); + DateTime d1 = Utils.getDateTimeFromString(strval.substring(0, strval.indexOf(":"))); + DateTime d2 = Utils.getDateTimeFromString(strval.substring(strval.indexOf(":") + 1)); return new DateTime[]{d1, d2}; } diff --git a/src/main/java/org/opensrp/web/rest/TaskResource.java b/src/main/java/org/opensrp/web/rest/TaskResource.java index ad5c4bf12..662f2075e 100644 --- a/src/main/java/org/opensrp/web/rest/TaskResource.java +++ b/src/main/java/org/opensrp/web/rest/TaskResource.java @@ -251,7 +251,7 @@ public ResponseEntity findIds(@RequestParam(value = SERVER_VERSION) @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> taskIdsPair = taskService.findAllTaskIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateTimeFromString(fromDate), Utils.getDateTimeFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(taskIdsPair.getLeft()); identifiers.setLastServerVersion(taskIdsPair.getRight()); diff --git a/src/main/java/org/opensrp/web/utils/Utils.java b/src/main/java/org/opensrp/web/utils/Utils.java index 210561d67..75200d81d 100644 --- a/src/main/java/org/opensrp/web/utils/Utils.java +++ b/src/main/java/org/opensrp/web/utils/Utils.java @@ -5,6 +5,7 @@ import java.util.Date; import java.util.List; +import java.util.Objects; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; @@ -26,15 +27,19 @@ public static String getStringFromJSON(JSONObject jsonObject, String key) { } } - public static Date getDateTimeFromString(@Nullable String date) { + public static Date getDateFromString(@Nullable String date) { + return Objects.requireNonNull(getDateTimeFromString(date)).toDate(); + } + + public static DateTime getDateTimeFromString(@Nullable String date) { if (StringUtils.isNotBlank(date)) { try { Long aLong = Long.parseLong(date); - return new DateTime(aLong).toDate(); + return new DateTime(aLong); } catch (NumberFormatException e) { try { - return new DateTime(date).toDate(); + return new DateTime(date); } catch (IllegalArgumentException illegalArgumentException) { return null; diff --git a/src/test/java/org/opensrp/web/utils/UtilsTest.java b/src/test/java/org/opensrp/web/utils/UtilsTest.java index f8c48891e..4d62726a1 100644 --- a/src/test/java/org/opensrp/web/utils/UtilsTest.java +++ b/src/test/java/org/opensrp/web/utils/UtilsTest.java @@ -45,7 +45,7 @@ public void testGetStringFromJSONForArray() { @Test public void testGetDateTimeFromStringShouldReturnDate(){ - Date date = Utils.getDateTimeFromString("1615895228000"); + Date date = Utils.getDateFromString("1615895228000"); Assert.assertNotNull(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); @@ -56,9 +56,9 @@ public void testGetDateTimeFromStringShouldReturnDate(){ @Test public void testGetDateTimeFromStringShouldReturnNull(){ - Date date = Utils.getDateTimeFromString("wrongdate"); + Date date = Utils.getDateFromString("wrongdate"); Assert.assertNull(date); - date = Utils.getDateTimeFromString(null); + date = Utils.getDateFromString(null); Assert.assertNull(date); } From 69de169019e187c10d81e877720f4e86531f50dc Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 13 Jan 2023 11:56:20 +0300 Subject: [PATCH 15/27] Trigger checks From 042c9a1978e526bed05a61a94e1e9df5a393d63a Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 13 Jan 2023 17:20:09 +0300 Subject: [PATCH 16/27] fix nullpointerexception from Utils class --- pom.xml | 2 +- .../org/opensrp/web/config/security/SecurityConfig.java | 3 ++- src/main/java/org/opensrp/web/utils/Utils.java | 6 +++++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index bced9f9c1..010f27976 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 6.1.6.RELEASE always 1.5.1 - 3.2.8-SNAPSHOT + 3.2.8-LOCAL-NOAUTH1-SNAPSHOT 2.4.1-SNAPSHOT 2.0.1-SNAPSHOT 2.0.5 diff --git a/src/main/java/org/opensrp/web/config/security/SecurityConfig.java b/src/main/java/org/opensrp/web/config/security/SecurityConfig.java index 811a26584..ee72ec2d8 100644 --- a/src/main/java/org/opensrp/web/config/security/SecurityConfig.java +++ b/src/main/java/org/opensrp/web/config/security/SecurityConfig.java @@ -113,7 +113,8 @@ protected void configure(HttpSecurity http) throws Exception { .ignoringAntMatchers("/rest/**","/multimedia/**","/actions/**") .and() .logout() - .logoutRequestMatcher(new AntPathRequestMatcher("logout.do", "GET")); + .logoutRequestMatcher(new AntPathRequestMatcher("logout.do", "GET")) + .and().headers().httpStrictTransportSecurity().includeSubDomains(true).maxAgeInSeconds(31536000);; /* @formatter:on */ } diff --git a/src/main/java/org/opensrp/web/utils/Utils.java b/src/main/java/org/opensrp/web/utils/Utils.java index 75200d81d..96abe2250 100644 --- a/src/main/java/org/opensrp/web/utils/Utils.java +++ b/src/main/java/org/opensrp/web/utils/Utils.java @@ -28,7 +28,11 @@ public static String getStringFromJSON(JSONObject jsonObject, String key) { } public static Date getDateFromString(@Nullable String date) { - return Objects.requireNonNull(getDateTimeFromString(date)).toDate(); + DateTime dateTime = getDateTimeFromString(date); + if(dateTime != null){ + return dateTime.toDate(); + } + return null; } public static DateTime getDateTimeFromString(@Nullable String date) { From 4df76a418b2d71284c9cd1186362af63146bc39f Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 13 Jan 2023 17:29:17 +0300 Subject: [PATCH 17/27] use valid opensrp-server-core version --- pom.xml | 2 +- .../java/org/opensrp/web/config/security/SecurityConfig.java | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 010f27976..bced9f9c1 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 6.1.6.RELEASE always 1.5.1 - 3.2.8-LOCAL-NOAUTH1-SNAPSHOT + 3.2.8-SNAPSHOT 2.4.1-SNAPSHOT 2.0.1-SNAPSHOT 2.0.5 diff --git a/src/main/java/org/opensrp/web/config/security/SecurityConfig.java b/src/main/java/org/opensrp/web/config/security/SecurityConfig.java index ee72ec2d8..811a26584 100644 --- a/src/main/java/org/opensrp/web/config/security/SecurityConfig.java +++ b/src/main/java/org/opensrp/web/config/security/SecurityConfig.java @@ -113,8 +113,7 @@ protected void configure(HttpSecurity http) throws Exception { .ignoringAntMatchers("/rest/**","/multimedia/**","/actions/**") .and() .logout() - .logoutRequestMatcher(new AntPathRequestMatcher("logout.do", "GET")) - .and().headers().httpStrictTransportSecurity().includeSubDomains(true).maxAgeInSeconds(31536000);; + .logoutRequestMatcher(new AntPathRequestMatcher("logout.do", "GET")); /* @formatter:on */ } From a5b90a54155766374b90aeaa85c2e6ee1ee2e477 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 16 Jan 2023 13:07:28 +0300 Subject: [PATCH 18/27] codacy fixe --- src/main/java/org/opensrp/web/utils/Utils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/opensrp/web/utils/Utils.java b/src/main/java/org/opensrp/web/utils/Utils.java index 96abe2250..56f21fa17 100644 --- a/src/main/java/org/opensrp/web/utils/Utils.java +++ b/src/main/java/org/opensrp/web/utils/Utils.java @@ -5,7 +5,6 @@ import java.util.Date; import java.util.List; -import java.util.Objects; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; From a7638bb6b7b0d2a698b56ab22bc80b7d56081427 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Tue, 17 Jan 2023 13:22:04 +0300 Subject: [PATCH 19/27] apply openmrs formatter --- .../org/opensrp/web/rest/ClientResource.java | 32 +- .../org/opensrp/web/rest/EventResource.java | 27 +- .../opensrp/web/rest/LocationResource.java | 71 +- .../org/opensrp/web/rest/PlanResource.java | 159 +++-- .../java/org/opensrp/web/rest/RestUtils.java | 398 ++++++----- .../org/opensrp/web/rest/SearchResource.java | 529 +++++++------- .../org/opensrp/web/rest/TaskResource.java | 114 +-- .../org/opensrp/web/utils/SearchHelper.java | 671 +++++++++--------- .../java/org/opensrp/web/utils/Utils.java | 7 +- .../opensrp/web/rest/SearchResourceTest.java | 120 ++-- .../opensrp/web/utils/SearchHelperTest.java | 626 ++++++++-------- .../java/org/opensrp/web/utils/UtilsTest.java | 32 +- 12 files changed, 1433 insertions(+), 1353 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/ClientResource.java b/src/main/java/org/opensrp/web/rest/ClientResource.java index 1681c2198..89f9aee42 100644 --- a/src/main/java/org/opensrp/web/rest/ClientResource.java +++ b/src/main/java/org/opensrp/web/rest/ClientResource.java @@ -22,7 +22,11 @@ import static org.opensrp.common.AllConstants.Event.LOCATION_ID; import java.text.ParseException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -129,7 +133,8 @@ public Client update(Client entity) {//TODO check if send property and id matche } @Override - public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params + public List search(HttpServletRequest request) + throws ParseException {//TODO search should not call different url but only add params List clients = new ArrayList<>(); ClientSearchBean searchBean = new ClientSearchBean(); searchBean.setNameLike(getStringFilter("name", request)); @@ -224,7 +229,8 @@ private List getDependants(List clients, String searchRelationsh List dependantClients = new ArrayList<>(); List clientsToRemove = new ArrayList<>(); for (Client client : clients) { - List dependants = clientService.findByRelationshipIdAndType(searchRelationship, client.getBaseEntityId()); + List dependants = clientService + .findByRelationshipIdAndType(searchRelationship, client.getBaseEntityId()); if (dependants.size() > 0) { dependantClients.addAll(dependants); } else { @@ -304,7 +310,8 @@ public ResponseEntity searchByCriteria(HttpServletRequest request) throw searchBean.setStartDate(startDate); DateTime endDate = getDateFilter(ENDDATE, request); searchBean.setEndDate(endDate); - } catch (ParseException e) { + } + catch (ParseException e) { logger.error(e.getMessage()); } @@ -376,7 +383,8 @@ private int getTotal(ClientSearchBean clientSearchBean, AddressSearchBean addres if (HOUSEHOLD.equalsIgnoreCase(clientType)) { total = clientService.findTotalCountHouseholdByCriteria(clientSearchBean, addressSearchBean).getTotalCount(); } else if (ALLCLIENTS.equalsIgnoreCase(clientType)) { - total = clientService.findTotalCountAllClientsByCriteria(clientSearchBean, addressSearchBean).getTotalCount(); + total = clientService.findTotalCountAllClientsByCriteria(clientSearchBean, addressSearchBean) + .getTotalCount(); } else if (ANC.equalsIgnoreCase(clientType)) { clientSearchBean.setClientType(null); total = clientService.findCountANCByCriteria(clientSearchBean, addressSearchBean); @@ -427,7 +435,7 @@ public ResponseEntity getAllChild(ClientSearchBean clientSearchBean, Add @RequestMapping(value = "/findIds", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findIds( - @RequestParam(value = SERVER_VERSIOIN) long serverVersion, + @RequestParam(value = SERVER_VERSIOIN) long serverVersion, @RequestParam(value = IS_ARCHIVED, defaultValue = FALSE, required = false) boolean isArchived, @RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate) { @@ -438,16 +446,16 @@ public ResponseEntity findIds( identifiers.setLastServerVersion(taskIdsPair.getRight()); return new ResponseEntity<>(identifiers, HttpStatus.OK); } - + /** * Fetch clients ordered by serverVersion ascending order * * @return a response with clients */ - @GetMapping(value = "/getAll", produces = {MediaType.APPLICATION_JSON_VALUE }) + @GetMapping(value = "/getAll", produces = { MediaType.APPLICATION_JSON_VALUE }) public List getAll( - @RequestParam(value = SERVER_VERSIOIN) long serverVersion, - @RequestParam(required = false, defaultValue = DEFAULT_LIMIT + "") int limit){ + @RequestParam(value = SERVER_VERSIOIN) long serverVersion, + @RequestParam(required = false, defaultValue = DEFAULT_LIMIT + "") int limit) { return clientService.findByServerVersion(serverVersion, limit); } @@ -457,9 +465,9 @@ public List getAll( * * @return a response with clients */ - @GetMapping(value = "/countAll", produces = {MediaType.APPLICATION_JSON_VALUE }) + @GetMapping(value = "/countAll", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity countAll( - @RequestParam(value = SERVER_VERSIOIN) long serverVersion){ + @RequestParam(value = SERVER_VERSIOIN) long serverVersion) { Long countOfClients = clientService.countAll(serverVersion); ModelMap modelMap = new ModelMap(); modelMap.put("count", countOfClients != null ? countOfClients : 0); diff --git a/src/main/java/org/opensrp/web/rest/EventResource.java b/src/main/java/org/opensrp/web/rest/EventResource.java index 1a9be2187..6daf22584 100755 --- a/src/main/java/org/opensrp/web/rest/EventResource.java +++ b/src/main/java/org/opensrp/web/rest/EventResource.java @@ -140,7 +140,8 @@ protected ResponseEntity sync(HttpServletRequest request) throws JsonPro if (team != null || providerId != null || locationId != null || baseEntityId != null || teamId != null) { - EventSyncBean eventSyncBean = sync(providerId, locationId, baseEntityId, serverVersion, team, teamId, limit, returnCount, false); + EventSyncBean eventSyncBean = sync(providerId, locationId, baseEntityId, serverVersion, team, teamId, limit, + returnCount, false); HttpHeaders headers = getJSONUTF8Headers(); if (returnCount) { @@ -202,7 +203,8 @@ protected ResponseEntity syncByPost(@RequestBody SyncParam syncParam) th * @return Events found matching the client IDs * @throws JsonProcessingException */ - @RequestMapping(value = "/sync-out-of-catchment", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) + @RequestMapping(value = "/sync-out-of-catchment", method = RequestMethod.GET, produces = { + MediaType.APPLICATION_JSON_VALUE }) protected ResponseEntity syncOutOfCatchment(HttpServletRequest request) throws JsonProcessingException { EventSyncBean response = new EventSyncBean(); @@ -216,7 +218,8 @@ protected ResponseEntity syncOutOfCatchment(HttpServletRequest request) boolean returnCount = Boolean.getBoolean(getStringFilter(RETURN_COUNT, request)); if (team != null || providerId != null || locationId != null || baseEntityId != null || teamId != null) { - EventSyncBean eventSyncBean = sync(providerId, locationId, baseEntityId, serverVersion, team, teamId, limit, returnCount, true); + EventSyncBean eventSyncBean = sync(providerId, locationId, baseEntityId, serverVersion, team, teamId, limit, + returnCount, true); HttpHeaders headers = getJSONUTF8Headers(); if (returnCount) { @@ -231,7 +234,8 @@ protected ResponseEntity syncOutOfCatchment(HttpServletRequest request) } @RequestMapping(value = "/sync-out-of-catchment", method = POST, produces = { MediaType.APPLICATION_JSON_VALUE }) - protected ResponseEntity syncOutOfCatchmentByPost(@RequestBody SyncParam syncParam) throws JsonProcessingException { + protected ResponseEntity syncOutOfCatchmentByPost(@RequestBody SyncParam syncParam) + throws JsonProcessingException { EventSyncBean response = new EventSyncBean(); try { @@ -343,7 +347,8 @@ public EventSyncBean sync(String providerId, String locationId, String baseEntit return getEventsAndClients(eventSearchBean, limit == null || limit == 0 ? 25 : limit, returnCount, isOutOfCatchment); } - private EventSyncBean getEventsAndClients(EventSearchBean eventSearchBean, Integer limit, boolean returnCount, boolean isOutOfCatchment) { + private EventSyncBean getEventsAndClients(EventSearchBean eventSearchBean, Integer limit, boolean returnCount, + boolean isOutOfCatchment) { List events = new ArrayList(); List clientIds = new ArrayList(); List clients = new ArrayList(); @@ -406,7 +411,8 @@ private List getEvents(EventSearchBean eventSearchBean, Integer limit, bo List relationships = getRelationships(baseEntityIds); eventSearchBean.setBaseEntityId(eventSearchBean.getBaseEntityId() + "," + String.join(",", relationships)); - return eventService.findOutOfCatchmentEvents(eventSearchBean, BaseEntity.SERVER_VERSIOIN, "asc", limit == null ? 25 : limit); + return eventService.findOutOfCatchmentEvents(eventSearchBean, BaseEntity.SERVER_VERSIOIN, "asc", + limit == null ? 25 : limit); } else { return eventService.findEvents(eventSearchBean, BaseEntity.SERVER_VERSIOIN, "asc", limit == null ? 25 : limit); } @@ -449,7 +455,8 @@ protected ResponseEntity getAll(@RequestParam long serverVersion, eventSearchBean.setServerVersion(serverVersion > 0 ? serverVersion + 1 : serverVersion); eventSearchBean.setEventType(eventType); return new ResponseEntity<>( - objectMapper.writeValueAsString(getEventsAndClients(eventSearchBean, limit == null ? 25 : limit, false, false)), + objectMapper + .writeValueAsString(getEventsAndClients(eventSearchBean, limit == null ? 25 : limit, false, false)), getJSONUTF8Headers(), OK); } @@ -509,7 +516,8 @@ public ResponseEntity save(@RequestBody String data, Authentication auth clientService.addorUpdate(client); } catch (Exception e) { - logger.error("[SYNC_INFO] Sync failed for client {}; identifiers: {}", client.getBaseEntityId(), gson.toJson(client.getIdentifiers()), e); + logger.error("[SYNC_INFO] Sync failed for client {}; identifiers: {}", client.getBaseEntityId(), + gson.toJson(client.getIdentifiers()), e); failedClientsIds.add(client.getBaseEntityId()); } } @@ -528,7 +536,8 @@ public ResponseEntity save(@RequestBody String data, Authentication auth event = eventService.processOutOfArea(event); eventService.addorUpdateEvent(event, username); - logger.info("[SYNC_INFO] Event {} of type {} saved", event.getFormSubmissionId(), event.getEventType()); + logger.info("[SYNC_INFO] Event {} of type {} saved", event.getFormSubmissionId(), + event.getEventType()); } catch (Exception e) { logger.error( diff --git a/src/main/java/org/opensrp/web/rest/LocationResource.java b/src/main/java/org/opensrp/web/rest/LocationResource.java index 07f47cf7e..2ec9d9b96 100644 --- a/src/main/java/org/opensrp/web/rest/LocationResource.java +++ b/src/main/java/org/opensrp/web/rest/LocationResource.java @@ -112,13 +112,13 @@ public class LocationResource { public static final String DEFAULT_PAGE_SIZE = "1000"; public static final String RETURN_TAGS = "return_tags"; - + public static final String RETURN_STRUCTURE_COUNT = "return_structure_count"; public static final String INCLUDE_INACTIVE = "includeInactive"; private PhysicalLocationService locationService; - + private PlanService planService; private DHIS2ImportOrganizationUnits dhis2ImportOrganizationUnits; @@ -129,7 +129,7 @@ public class LocationResource { public void setLocationService(PhysicalLocationService locationService) { this.locationService = locationService; } - + @Autowired public void setPlanService(PlanService planService) { this.planService = planService; @@ -173,15 +173,15 @@ public ResponseEntity getLocations(@RequestBody LocationSyncRequestWrapp Boolean isJurisdiction = locationSyncRequestWrapper.getIsJurisdiction(); String locationNames = StringUtils.join(locationSyncRequestWrapper.getLocationNames(), ","); String parentIds = StringUtils.join(locationSyncRequestWrapper.getParentId(), ","); - List locationIds=locationSyncRequestWrapper.getLocationIds(); + List locationIds = locationSyncRequestWrapper.getLocationIds(); boolean returnCount = locationSyncRequestWrapper.isReturnCount(); HttpHeaders headers = RestUtils.getJSONUTF8Headers(); Long locationCount = 0l; if (isJurisdiction) { - String locations="[]"; + String locations = "[]"; if (locationIds != null && !locationIds.isEmpty()) { - locations = gson.toJson(locationService.findLocationsByIds(true, locationIds,currentServerVersion)); + locations = gson.toJson(locationService.findLocationsByIds(true, locationIds, currentServerVersion)); if (returnCount) { locationCount = locationService.countLocationsByIds(locationIds, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(locationCount)); @@ -207,19 +207,23 @@ public ResponseEntity getLocations(@RequestBody LocationSyncRequestWrapp return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - String structures = gson.toJson(locationService.findStructuresByParentAndServerVersion(parentIds, currentServerVersion)); - if (returnCount){ - Long structureCount = locationService.countStructuresByParentAndServerVersion(parentIds, currentServerVersion); + String structures = gson + .toJson(locationService.findStructuresByParentAndServerVersion(parentIds, currentServerVersion)); + if (returnCount) { + Long structureCount = locationService + .countStructuresByParentAndServerVersion(parentIds, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(structureCount)); } return new ResponseEntity<>(structures, headers, HttpStatus.OK); } } - @RequestMapping(value = "/findStructuresByAncestor", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity getStructuresByAncestor(@RequestParam(name = "id") final String ancestorId){ + @RequestMapping(value = "/findStructuresByAncestor", method = RequestMethod.GET, produces = { + MediaType.APPLICATION_JSON_VALUE }) + public ResponseEntity getStructuresByAncestor(@RequestParam(name = "id") final String ancestorId) { final long serverVersion = 0L; - List locationAndTheirChildren = locationService.findLocationByIdWithChildren(false, ancestorId, Integer.MAX_VALUE); + List locationAndTheirChildren = locationService + .findLocationByIdWithChildren(false, ancestorId, Integer.MAX_VALUE); String parentIds = locationAndTheirChildren.stream() .map(PhysicalLocation::getId) .collect(Collectors.joining(",")); @@ -247,14 +251,14 @@ public ResponseEntity getLocationsTwo(@RequestParam(BaseEntity.SERVER_VE if (isJurisdiction) { if (StringUtils.isBlank(locationNames)) { String locations = gson.toJson(locationService.findLocationsByServerVersion(currentServerVersion)); - if (returnCount){ + if (returnCount) { locationCount = locationService.countLocationsByServerVersion(currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(locationCount)); } return new ResponseEntity<>(locations, headers, HttpStatus.OK); } String locations = gson.toJson(locationService.findLocationsByNames(locationNames, currentServerVersion)); - if (returnCount){ + if (returnCount) { locationCount = locationService.countLocationsByNames(locationNames, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(locationCount)); } @@ -264,9 +268,11 @@ public ResponseEntity getLocationsTwo(@RequestParam(BaseEntity.SERVER_VE if (StringUtils.isBlank(parentIds)) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - String structures = gson.toJson(locationService.findStructuresByParentAndServerVersion(parentIds, currentServerVersion)); - if (returnCount){ - Long structureCount = locationService.countStructuresByParentAndServerVersion(parentIds, currentServerVersion); + String structures = gson + .toJson(locationService.findStructuresByParentAndServerVersion(parentIds, currentServerVersion)); + if (returnCount) { + Long structureCount = locationService + .countStructuresByParentAndServerVersion(parentIds, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(structureCount)); } return new ResponseEntity<>(structures, headers, HttpStatus.OK); @@ -284,7 +290,7 @@ public ResponseEntity create(@RequestBody String entity, return new ResponseEntity<>(HttpStatus.CREATED); } catch (JsonSyntaxException e) { - logger.error("The request doesnt contain a valid location representation",e); + logger.error("The request doesnt contain a valid location representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -300,7 +306,7 @@ public ResponseEntity update(@RequestBody String entity, return new ResponseEntity<>(HttpStatus.CREATED); } catch (JsonSyntaxException e) { - logger.error("The request doesnt contain a valid location representation",e); + logger.error("The request doesnt contain a valid location representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -323,7 +329,7 @@ public ResponseEntity saveBatch(@RequestBody String entity, } catch (JsonSyntaxException e) { - logger.error("The request doesnt contain a valid location representation",e); + logger.error("The request doesnt contain a valid location representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -364,7 +370,7 @@ public ResponseEntity findByLocationProperties( if (filterArray.length == 2 && (PARENT_ID.equalsIgnoreCase(filterArray[0]) || PARENT_ID_NO_UNDERSCORE.equalsIgnoreCase(filterArray[0]))) { parentId = Constants.NULL.equalsIgnoreCase(filterArray[1]) || StringUtils.isBlank(filterArray[1]) - ? "" : filterArray [1]; + ? "" : filterArray[1]; } else if (filterArray.length == 2) { filters.put(filterArray[0], filterArray[1]); @@ -435,12 +441,13 @@ public ResponseEntity findByIdWithChildren( @RequestMapping(value = "/findStructureIds", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findIds( - @RequestParam(value = SERVER_VERSION) long serverVersion, + @RequestParam(value = SERVER_VERSION) long serverVersion, @RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate) { - Pair, Long> structureIdsPair = locationService.findAllStructureIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); + Pair, Long> structureIdsPair = locationService + .findAllStructureIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(structureIdsPair.getLeft()); identifiers.setLastServerVersion(structureIdsPair.getRight()); @@ -478,7 +485,9 @@ public ResponseEntity getAll( RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } else { return new ResponseEntity<>( - gson.toJson(locationService.findAllStructures(returnGeometry, serverVersion, pageLimit, pageNumber, orderByType, orderByFieldName)), + gson.toJson(locationService + .findAllStructures(returnGeometry, serverVersion, pageLimit, pageNumber, orderByType, + orderByFieldName)), RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } @@ -520,12 +529,13 @@ public ResponseEntity countAll( @RequestMapping(value = "/findLocationIds", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findLocationIds( - @RequestParam(value = SERVER_VERSION) long serverVersion, + @RequestParam(value = SERVER_VERSION) long serverVersion, @RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate) { - Pair, Long> locationIdsPair = locationService.findAllLocationIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); + Pair, Long> locationIdsPair = locationService + .findAllLocationIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(locationIdsPair.getLeft()); identifiers.setLastServerVersion(locationIdsPair.getRight()); @@ -574,7 +584,7 @@ public ResponseEntity generateLocationTree( return new ResponseEntity<>(gson.toJson(tree), RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + @RequestMapping(value = "/hierarchy/plan/{plan}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity generateLocationTreeForPlan( @@ -603,7 +613,7 @@ public ResponseEntity generateLocationTreeForPlan( @PostMapping(value = "/dhis2/import", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) - public ResponseEntity importLocations(@RequestParam(value = "startPage",required = false) String startPage, + public ResponseEntity importLocations(@RequestParam(value = "startPage", required = false) String startPage, @RequestParam("beginning") Boolean beginning) { final String DHIS_IMPORT_JOB_STATUS_END_POINT = "/rest/location/dhis2/status"; @@ -641,7 +651,6 @@ public Set generateLocationTreeWithAncestors(@PathVariable("loca return locationService.buildLocationHeirarchyWithAncestors(locationId); } - @Data static class LocationSyncRequestWrapper { diff --git a/src/main/java/org/opensrp/web/rest/PlanResource.java b/src/main/java/org/opensrp/web/rest/PlanResource.java index 1d5f0dd15..6993167d0 100644 --- a/src/main/java/org/opensrp/web/rest/PlanResource.java +++ b/src/main/java/org/opensrp/web/rest/PlanResource.java @@ -61,16 +61,16 @@ @Controller @RequestMapping(value = "/rest/plans") public class PlanResource { - + private static Logger logger = LogManager.getLogger(PlanResource.class.toString()); - + public static Gson gson = new GsonBuilder() .registerTypeAdapter(DateTime.class, new TaskDateTimeTypeConverter("yyyy-MM-dd")) - .registerTypeAdapter(LocalDate.class, new DateTypeConverter()) + .registerTypeAdapter(LocalDate.class, new DateTypeConverter()) .registerTypeAdapter(Time.class, new TimingRepeatTimeTypeConverter()).create(); - + private PlanService planService; - + private PhysicalLocationService locationService; private static final String IS_DELETED = "is_deleted"; @@ -78,11 +78,11 @@ public class PlanResource { private static final String FALSE = "false"; public static final String OPERATIONAL_AREA_ID = "operational_area_id"; - + public static final String IDENTIFIERS = "identifiers"; - + public static final String FIELDS = "fields"; - + public static final String USERNAME = "username"; public static final String IS_TEMPLATE = "is_template"; @@ -90,32 +90,34 @@ public class PlanResource { public static final String PLAN_STATUS = "planStatus"; public static final String USE_CONTEXT = "useContext"; - + public static final String OPENSRP_EVENT_ID = "opensrpEventId"; @Autowired public void setPlanService(PlanService planService) { this.planService = planService; } - + @Autowired public void setLocationService(PhysicalLocationService locationService) { this.locationService = locationService; } - + @RequestMapping(value = "/{identifier}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getPlanByUniqueId(@PathVariable("identifier") String identifier, - @RequestParam(value = FIELDS, required = false) List fields , @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { + @RequestParam(value = FIELDS, required = false) List fields, + @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { if (identifier == null) { return new ResponseEntity<>("Plan Id is required", HttpStatus.BAD_REQUEST); } return new ResponseEntity<>( - gson.toJson(planService.getPlansByIdsReturnOptionalFields(Collections.singletonList(identifier), fields, isTemplateParam)), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + gson.toJson(planService + .getPlansByIdsReturnOptionalFields(Collections.singletonList(identifier), fields, isTemplateParam)), + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + @RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getPlans(@RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam, @RequestParam(value = PAGE_NUMBER, required = false) Integer pageNumber, @@ -123,7 +125,7 @@ public ResponseEntity getPlans(@RequestParam(value = IS_TEMPLATE, requir @RequestParam(value = ORDER_BY_TYPE, required = false) String orderByType, @RequestParam(value = ORDER_BY_FIELD_NAME, required = false) String orderByFieldName, @RequestParam(value = PLAN_STATUS, required = false) String planStatus, - @RequestParam(value = USE_CONTEXT, required = false) List useContextList) { + @RequestParam(value = USE_CONTEXT, required = false) List useContextList) { Map useContextFilters = null; if (useContextList != null) { @@ -135,31 +137,35 @@ public ResponseEntity getPlans(@RequestParam(value = IS_TEMPLATE, requir } } } - PlanSearchBean planSearchBean = createPlanSearchBean(isTemplateParam, pageNumber, pageSize, orderByType, orderByFieldName, planStatus, useContextFilters); - return new ResponseEntity<>(gson.toJson(planService.getAllPlans(planSearchBean)),RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + PlanSearchBean planSearchBean = createPlanSearchBean(isTemplateParam, pageNumber, pageSize, orderByType, + orderByFieldName, planStatus, useContextFilters); + return new ResponseEntity<>(gson.toJson(planService.getAllPlans(planSearchBean)), RestUtils.getJSONUTF8Headers(), + HttpStatus.OK); } - + @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity create(@RequestBody String entity, Authentication authentication) { try { PlanDefinition plan = gson.fromJson(entity, PlanDefinition.class); - - //check whether a case triggered plan with a given opensrp event id exists + + //check whether a case triggered plan with a given opensrp event id exists PlanDefinition.UseContext opensrpEventIdUseContext = getUseContextWithCode(plan, OPENSRP_EVENT_ID); if (opensrpEventIdUseContext != null && !isValidCaseTriggeredPlan(opensrpEventIdUseContext)) { - return new ResponseEntity<>("Case triggered plan with opensrpEventId " + opensrpEventIdUseContext.getValueCodableConcept() + " already exists", HttpStatus.CONFLICT); + return new ResponseEntity<>( + "Case triggered plan with opensrpEventId " + opensrpEventIdUseContext.getValueCodableConcept() + + " already exists", HttpStatus.CONFLICT); } - + planService.addPlan(plan, RestUtils.currentUser(authentication).getUsername()); return new ResponseEntity<>(HttpStatus.CREATED); } catch (JsonSyntaxException e) { - logger.error("The request doesn't contain a valid plan representation",e); + logger.error("The request doesn't contain a valid plan representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } - + @RequestMapping(method = RequestMethod.PUT, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity update(@RequestBody String entity, Authentication authentication) { try { @@ -173,12 +179,13 @@ public ResponseEntity update(@RequestBody String entity, Authenticat } } - + @RequestMapping(value = "/sync", method = RequestMethod.POST, consumes = { - MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) + MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity syncByServerVersionAndAssignedPlansOnOrganization( - @RequestBody PlanSyncRequestWrapper planSyncRequestWrapper, Authentication authentication, @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { - + @RequestBody PlanSyncRequestWrapper planSyncRequestWrapper, Authentication authentication, + @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { + List operationalAreaIds = planSyncRequestWrapper.getOperationalAreaId(); String username = null; if (authentication != null) @@ -194,30 +201,33 @@ public ResponseEntity syncByServerVersionAndAssignedPlansOnOrganization( planSyncRequestWrapper.getServerVersion(), isTemplateParam); if (planSyncRequestWrapper.isReturnCount()) { planCount = planService.countPlansByOrganizationsAndServerVersion(planSyncRequestWrapper.organizations, - planSyncRequestWrapper.getServerVersion()); + planSyncRequestWrapper.getServerVersion()); } } else if (username != null) { - plans = planService.getPlansByUsernameAndServerVersion(username, planSyncRequestWrapper.getServerVersion(), isTemplateParam); + plans = planService.getPlansByUsernameAndServerVersion(username, planSyncRequestWrapper.getServerVersion(), + isTemplateParam); if (planSyncRequestWrapper.isReturnCount()) { - planCount = planService.countPlansByUsernameAndServerVersion(username, planSyncRequestWrapper.getServerVersion()); + planCount = planService + .countPlansByUsernameAndServerVersion(username, planSyncRequestWrapper.getServerVersion()); } } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } HttpHeaders headers = RestUtils.getJSONUTF8Headers(); - if (planSyncRequestWrapper.isReturnCount()){ + if (planSyncRequestWrapper.isReturnCount()) { headers.add(TOTAL_RECORDS, String.valueOf(planCount)); } return new ResponseEntity<>(gson.toJson(plans), headers, HttpStatus.OK); } - + // here for backward compatibility @RequestMapping(value = "/sync", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity syncByServerVersionAndOperationalAreaTwo(HttpServletRequest request, - @RequestParam(value = OPERATIONAL_AREA_ID) List operationalAreaIds , @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { + @RequestParam(value = OPERATIONAL_AREA_ID) List operationalAreaIds, + @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { String serverVersion = getStringFilter(SERVER_VERSIOIN, request); long currentServerVersion = 0; try { @@ -231,25 +241,26 @@ public ResponseEntity syncByServerVersionAndOperationalAreaTwo(HttpServl } return new ResponseEntity<>( - gson.toJson(planService.getPlansByServerVersionAndOperationalArea(currentServerVersion, operationalAreaIds, isTemplateParam)), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + gson.toJson(planService.getPlansByServerVersionAndOperationalArea(currentServerVersion, operationalAreaIds, + isTemplateParam)), + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + /** * This method provides an API endpoint that searches for plans using a list of provided plan * identifiers and returns a subset of fields determined by the list of provided fields If no * plan identifier(s) are provided the method returns all available plans If no fields are * provided the method returns all the available fields - * + * * @param identifiers list of plan identifiers - * @param fields list of fields to return + * @param fields list of fields to return * @return plan definitions whose identifiers match the provided params */ @RequestMapping(value = "/findByIdsWithOptionalFields", method = RequestMethod.GET, produces = { - MediaType.APPLICATION_JSON_VALUE }) + MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findByIdentifiersReturnOptionalFields(HttpServletRequest request, - @RequestParam(value = IDENTIFIERS) List identifiers, - @RequestParam(value = FIELDS, required = false) List fields, + @RequestParam(value = IDENTIFIERS) List identifiers, + @RequestParam(value = FIELDS, required = false) List fields, @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { if (fields != null && !fields.isEmpty()) { @@ -259,10 +270,11 @@ public ResponseEntity findByIdentifiersReturnOptionalFields(HttpServletR } } } - return new ResponseEntity<>(gson.toJson(planService.getPlansByIdsReturnOptionalFields(identifiers, fields, isTemplateParam)), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + return new ResponseEntity<>( + gson.toJson(planService.getPlansByIdsReturnOptionalFields(identifiers, fields, isTemplateParam)), + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + /** * This method provides an endpoint that searches for location details i.e. identifier and name * using a provided plan identifier @@ -271,28 +283,29 @@ public ResponseEntity findByIdentifiersReturnOptionalFields(HttpServletR * @return A list of location names and identifiers */ @RequestMapping(value = "/findLocationNames/{planIdentifier}", method = RequestMethod.GET, produces = { - MediaType.APPLICATION_JSON_VALUE }) + MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity> findLocationDetailsByPlanId( - @PathVariable("planIdentifier") String planIdentifier) { + @PathVariable("planIdentifier") String planIdentifier) { return new ResponseEntity<>(locationService.findLocationDetailsByPlanId(planIdentifier), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } /** * Fetch plans ordered by serverVersion ascending * * @param serverVersion serverVersion using to filter by - * @param limit upper limit on number os plas to fetch + * @param limit upper limit on number os plas to fetch * @return A list of plan definitions */ @RequestMapping(value = "/getAll", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getAll(@RequestParam(value = SERVER_VERSIOIN) long serverVersion, - @RequestParam(value = LIMIT, required = false) Integer limit, @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { + @RequestParam(value = LIMIT, required = false) Integer limit, + @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { Integer pageLimit = limit == null ? DEFAULT_LIMIT : limit; return new ResponseEntity<>(gson.toJson(planService.getAllPlans(serverVersion, pageLimit, isTemplateParam)), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } @@ -319,9 +332,9 @@ public ResponseEntity countAll(@RequestParam(value = SERVER_VERSIOIN) */ @RequestMapping(value = "/findIds", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findIds(@RequestParam(value = SERVER_VERSIOIN, required = false) long serverVersion, - @RequestParam(value = IS_DELETED, defaultValue = FALSE, required = false) boolean isDeleted, - @RequestParam(value = "fromDate", required = false) String fromDate, - @RequestParam(value = "toDate", required = false) String toDate) { + @RequestParam(value = IS_DELETED, defaultValue = FALSE, required = false) boolean isDeleted, + @RequestParam(value = "fromDate", required = false) String fromDate, + @RequestParam(value = "toDate", required = false) String toDate) { Pair, Long> planIdsPair = planService.findAllIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, isDeleted, Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); @@ -339,15 +352,16 @@ public ResponseEntity findIds(@RequestParam(value = SERVER_VERSIOIN, * @param username * @return plan definitions whose identifiers match the provided param */ - @RequestMapping(value = "/user/{username:.+}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) + @RequestMapping(value = "/user/{username:.+}", method = RequestMethod.GET, produces = { + MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity fetchPlansForUser(@PathVariable(USERNAME) String username, - @RequestParam(value = SERVER_VERSIOIN, required = false) String serverVersion, + @RequestParam(value = SERVER_VERSIOIN, required = false) String serverVersion, @RequestParam(value = IS_TEMPLATE, required = false) boolean isTemplateParam) { - + if (StringUtils.isBlank(username)) { return new ResponseEntity<>("Request Param missing", RestUtils.getJSONUTF8Headers(), HttpStatus.BAD_REQUEST); } - + long currentServerVersion = 0; try { currentServerVersion = Long.parseLong(serverVersion); @@ -363,7 +377,7 @@ public ResponseEntity fetchPlansForUser(@PathVariable(USERNAME) String u return new ResponseEntity<>(gson.toJson(plans), RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + public boolean doesObjectContainField(Object object, String fieldName) { Class objectClass = object.getClass(); for (Field field : objectClass.getDeclaredFields()) { @@ -376,34 +390,33 @@ else if (sName == null && field.getName().equals(fieldName)) { } return false; } - + static class PlanSyncRequestWrapper { - + @JsonProperty("operational_area_id") private List operationalAreaId; - + @JsonProperty private long serverVersion; - + @JsonProperty private List organizations; - + @JsonProperty(RETURN_COUNT) private boolean returnCount; public List getOperationalAreaId() { return operationalAreaId; } - + public long getServerVersion() { return serverVersion; } - + public List getOrganizations() { return organizations; } - public boolean isReturnCount() { return returnCount; } @@ -430,14 +443,15 @@ private PlanSearchBean createPlanSearchBean(boolean isTemplateParam, Integer pag return planSearchBean; } - + /** * This method retrieves a usecontext with a particular code from a plan + * * @param plan * @return PlanDefinition.UseContext */ private PlanDefinition.UseContext getUseContextWithCode(PlanDefinition plan, String useContextCode) { - for (PlanDefinition.UseContext useContext: plan.getUseContext() ) { + for (PlanDefinition.UseContext useContext : plan.getUseContext()) { if (useContext.getCode().equalsIgnoreCase(useContextCode)) { return useContext; } @@ -448,16 +462,17 @@ private PlanDefinition.UseContext getUseContextWithCode(PlanDefinition plan, Str /** * This method validates whether there is an existing case triggered * plan for a given opensrpEventId + * * @param useContext useContext that contains the opensrpEventId * @return boolean whether the plan is valid (it's not a duplicate) */ private boolean isValidCaseTriggeredPlan(PlanDefinition.UseContext useContext) { Map useContextFilters = new HashMap<>(); - useContextFilters.put(useContext.getCode(),useContext.getValueCodableConcept()); + useContextFilters.put(useContext.getCode(), useContext.getValueCodableConcept()); PlanSearchBean planSearchBean = createPlanSearchBean(false, 0, 5, null, null, null, useContextFilters); List plans = planService.getAllPlans(planSearchBean); return (plans != null && !plans.isEmpty()) ? false : true; } - + } diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 787f4962f..50d1c567a 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -32,199 +32,209 @@ import java.util.zip.ZipOutputStream; public class RestUtils { - public static final String DATE_FORMAT = "dd-MM-yyyy"; - public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy"); - public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; - public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm"); - - private static final Logger logger = LogManager.getLogger(RestUtils.class.toString()); - - - public static String getStringFilter(String filter, HttpServletRequest req) { - return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter); - } - - public static String getStringFilter(String filter, JSONObject jsonObject) { - return StringUtils.isBlank(jsonObject.optString(filter)) ? null : jsonObject.optString(filter); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) { - String filterVal = getStringFilter(filter, req); - if (filterVal != null) { - return Enum.valueOf(cls, filterVal); - } - return null; - } - - public static Integer getIntegerFilter(String filter, HttpServletRequest req) { - String strval = getStringFilter(filter, req); - return strval == null ? null : Integer.parseInt(strval); - } - - public static Float getFloatFilter(String filter, HttpServletRequest req) { - String strval = getStringFilter(filter, req); - return strval == null ? null : Float.parseFloat(strval); - } - - public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException { - String strval = getStringFilter(filter, req); - return strval == null ? null : new DateTime(strval); - } - - public static DateTime[] getDateRangeFilter(String filter, Object object) throws ParseException { - String strval; - - if(object instanceof HttpServletRequest){ - HttpServletRequest req = (HttpServletRequest) object; - strval = getStringFilter(filter, req); - } else { - JSONObject jsonObject = (JSONObject) object; - strval = getStringFilter(filter, jsonObject); - } - - if (strval == null) { - return null; - } - if (!strval.contains(":")) { - return new DateTime[]{Utils.getDateTimeFromString(strval),Utils.getDateTimeFromString(strval)}; - } - DateTime d1 = Utils.getDateTimeFromString(strval.substring(0, strval.indexOf(":"))); - DateTime d2 = Utils.getDateTimeFromString(strval.substring(strval.indexOf(":") + 1)); - return new DateTime[]{d1, d2}; - } - - public static boolean getBooleanFilter(String filter, HttpServletRequest req) { - String stringFilter = getStringFilter(filter, req); - return Boolean.parseBoolean(stringFilter); - } - - public static void main(String[] args) { - System.out.println(new DateTime("​1458932400000")); - } - - public static synchronized String setDateFilter(Date date) throws ParseException { - return date == null ? null : SDF.format(date); - } - - public static void verifyRequiredProperties(List properties, T entity) { - if (properties != null) - for (String p : properties) { - Field[] aaa = entity.getClass().getDeclaredFields(); - for (Field field : aaa) { - if (field.getName().equals(p)) { - field.setAccessible(true); - try { - if (field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")) { - throw new RuntimeException("A required field " + p + " was found empty"); - } - } catch (IllegalArgumentException e) { - e.printStackTrace(); - throw new RuntimeException("A required field " + p + " was not found in resource class"); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - } - } - - public static HttpHeaders getJSONUTF8Headers() { - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add("Content-Type", "application/json; charset=utf-8"); - return responseHeaders; - } - - /** - * Zips multimedia files and writes content to {@param zipOutputStream} - * - * @param zipOutputStream - * @param multimediaFiles - * @throws IOException - */ - public static void zipFiles(ZipOutputStream zipOutputStream, List multimediaFiles, MultimediaFileManager fileManager) throws - IOException { - for (Multimedia multiMedia : multimediaFiles) { - FileInputStream inputStream; - File file = fileManager.retrieveFile(multiMedia.getFilePath()); - if (file != null) { - logger.info("Adding " + file.getName()); - zipOutputStream.putNextEntry(new ZipEntry(file.getName())); - try { - inputStream = new FileInputStream(file); - } catch (FileNotFoundException e) { - logger.warn("Could not find file " + file.getAbsolutePath()); - continue; - } - - // Write the contents of the file - BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); - int data; - while ((data = bufferedInputStream.read()) != -1) { - zipOutputStream.write(data); - } - bufferedInputStream.close(); - zipOutputStream.closeEntry(); - logger.info("Done downloading file " + file.getName()); - - // clean up temp files (may want to cache in future) - if (fileManager instanceof S3MultimediaFileManager) { - file.delete(); - } - } - } - } - - public static User currentUser(Authentication authentication) { - if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) { - @SuppressWarnings("unchecked") - KeycloakPrincipal kp = (KeycloakPrincipal) authentication - .getPrincipal(); - AccessToken token = kp.getKeycloakSecurityContext().getToken(); - User user = new User(authentication.getName()); - user.setPreferredName(token.getName()); - user.setUsername(token.getPreferredUsername()); - List authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority()) - .collect(Collectors.toList()); - user.setAttributes(token.getOtherClaims()); - user.setRoles(authorities); - user.setPermissions(authorities); - return user; - } - return null; - } - - public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException { - File aFile; - FileInputStream fis = null; - ZipEntry zipEntry; - String tempDirectory = System.getProperty("java.io.tmpdir"); - try { - if (StringUtils.isNotBlank(fileName)) { - aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName); - fis = new FileInputStream(aFile); - zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName); - logger.info("Writing file : '" + fileName + "' to zip file"); - } else { - fis = new FileInputStream(filePath); - zipEntry = new ZipEntry(filePath); - logger.info("Writing file : '" + filePath + "' to zip file"); - } - zipStream.putNextEntry(zipEntry); - byte[] bytes = new byte[1024]; - int length; - while ((length = fis.read(bytes)) >= 0) { - zipStream.write(bytes, 0, length); - } - - zipStream.closeEntry(); - } catch (IOException e) { - logger.error("IO Exception occurred: " + e.getMessage()); - } finally { - if (fis != null) { - fis.close(); - } - } - } + + public static final String DATE_FORMAT = "dd-MM-yyyy"; + + public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy"); + + public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; + + public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm"); + + private static final Logger logger = LogManager.getLogger(RestUtils.class.toString()); + + public static String getStringFilter(String filter, HttpServletRequest req) { + return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter); + } + + public static String getStringFilter(String filter, JSONObject jsonObject) { + return StringUtils.isBlank(jsonObject.optString(filter)) ? null : jsonObject.optString(filter); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) { + String filterVal = getStringFilter(filter, req); + if (filterVal != null) { + return Enum.valueOf(cls, filterVal); + } + return null; + } + + public static Integer getIntegerFilter(String filter, HttpServletRequest req) { + String strval = getStringFilter(filter, req); + return strval == null ? null : Integer.parseInt(strval); + } + + public static Float getFloatFilter(String filter, HttpServletRequest req) { + String strval = getStringFilter(filter, req); + return strval == null ? null : Float.parseFloat(strval); + } + + public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException { + String strval = getStringFilter(filter, req); + return strval == null ? null : new DateTime(strval); + } + + public static DateTime[] getDateRangeFilter(String filter, Object object) throws ParseException { + String strval; + + if (object instanceof HttpServletRequest) { + HttpServletRequest req = (HttpServletRequest) object; + strval = getStringFilter(filter, req); + } else { + JSONObject jsonObject = (JSONObject) object; + strval = getStringFilter(filter, jsonObject); + } + + if (strval != null) { + if (!strval.contains(":")) { + return new DateTime[] { Utils.getDateTimeFromString(strval), Utils.getDateTimeFromString(strval) }; + } + DateTime d1 = Utils.getDateTimeFromString(strval.substring(0, strval.indexOf(":"))); + DateTime d2 = Utils.getDateTimeFromString(strval.substring(strval.indexOf(":") + 1)); + return new DateTime[] { d1, d2 }; + } else { + return null; + } + } + + public static boolean getBooleanFilter(String filter, HttpServletRequest req) { + String stringFilter = getStringFilter(filter, req); + return Boolean.parseBoolean(stringFilter); + } + + public static void main(String[] args) { + System.out.println(new DateTime("​1458932400000")); + } + + public static synchronized String setDateFilter(Date date) throws ParseException { + return date == null ? null : SDF.format(date); + } + + public static void verifyRequiredProperties(List properties, T entity) { + if (properties != null) + for (String p : properties) { + Field[] aaa = entity.getClass().getDeclaredFields(); + for (Field field : aaa) { + if (field.getName().equals(p)) { + field.setAccessible(true); + try { + if (field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")) { + throw new RuntimeException("A required field " + p + " was found empty"); + } + } + catch (IllegalArgumentException e) { + e.printStackTrace(); + throw new RuntimeException("A required field " + p + " was not found in resource class"); + } + catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + } + + public static HttpHeaders getJSONUTF8Headers() { + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.add("Content-Type", "application/json; charset=utf-8"); + return responseHeaders; + } + + /** + * Zips multimedia files and writes content to {@param zipOutputStream} + * + * @param zipOutputStream + * @param multimediaFiles + * @throws IOException + */ + public static void zipFiles(ZipOutputStream zipOutputStream, List multimediaFiles, + MultimediaFileManager fileManager) throws + IOException { + for (Multimedia multiMedia : multimediaFiles) { + FileInputStream inputStream; + File file = fileManager.retrieveFile(multiMedia.getFilePath()); + if (file != null) { + logger.info("Adding " + file.getName()); + zipOutputStream.putNextEntry(new ZipEntry(file.getName())); + try { + inputStream = new FileInputStream(file); + } + catch (FileNotFoundException e) { + logger.warn("Could not find file " + file.getAbsolutePath()); + continue; + } + + // Write the contents of the file + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + int data; + while ((data = bufferedInputStream.read()) != -1) { + zipOutputStream.write(data); + } + bufferedInputStream.close(); + zipOutputStream.closeEntry(); + logger.info("Done downloading file " + file.getName()); + + // clean up temp files (may want to cache in future) + if (fileManager instanceof S3MultimediaFileManager) { + file.delete(); + } + } + } + } + + public static User currentUser(Authentication authentication) { + if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) { + @SuppressWarnings("unchecked") + KeycloakPrincipal kp = (KeycloakPrincipal) authentication + .getPrincipal(); + AccessToken token = kp.getKeycloakSecurityContext().getToken(); + User user = new User(authentication.getName()); + user.setPreferredName(token.getName()); + user.setUsername(token.getPreferredUsername()); + List authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority()) + .collect(Collectors.toList()); + user.setAttributes(token.getOtherClaims()); + user.setRoles(authorities); + user.setPermissions(authorities); + return user; + } + return null; + } + + public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException { + File aFile; + FileInputStream fis = null; + ZipEntry zipEntry; + String tempDirectory = System.getProperty("java.io.tmpdir"); + try { + if (StringUtils.isNotBlank(fileName)) { + aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName); + fis = new FileInputStream(aFile); + zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName); + logger.info("Writing file : '" + fileName + "' to zip file"); + } else { + fis = new FileInputStream(filePath); + zipEntry = new ZipEntry(filePath); + logger.info("Writing file : '" + filePath + "' to zip file"); + } + zipStream.putNextEntry(zipEntry); + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zipStream.write(bytes, 0, length); + } + + zipStream.closeEntry(); + } + catch (IOException e) { + logger.error("IO Exception occurred: " + e.getMessage()); + } + finally { + if (fis != null) { + fis.close(); + } + } + } } diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 227bb4f00..78a3be5e0 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -51,285 +51,296 @@ @RequestMapping(value = "/rest/search") public class SearchResource extends RestResource { - private static Logger logger = LogManager.getLogger(SearchResource.class.toString()); + private static Logger logger = LogManager.getLogger(SearchResource.class.toString()); - private SearchService searchService; + private SearchService searchService; - private ClientService clientService; + private ClientService clientService; - private EventService eventService; + private EventService eventService; - @Autowired - public SearchResource(SearchService searchService, ClientService clientService, EventService eventService) { - this.searchService = searchService; - this.clientService = clientService; - this.eventService = eventService; - } + @Autowired + public SearchResource(SearchService searchService, ClientService clientService, EventService eventService) { + this.searchService = searchService; + this.clientService = clientService; + this.eventService = eventService; + } - /** - * @param request contains search parameter of with attributes and full colon e.g - * 1. search?attributes=phone_number:072700000 - * or search parameter without attribute and without colon e.g - * 2. search?phone_number=072700000 - * @throws ParseException - */ - @Override - public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params - Pair> result = extractNamesAndCreateClientSearchBean(request); - return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); - } + /** + * @param request contains search parameter of with attributes and full colon e.g + * 1. search?attributes=phone_number:072700000 + * or search parameter without attribute and without colon e.g + * 2. search?phone_number=072700000 + * @throws ParseException + */ + @Override + public List search(HttpServletRequest request) + throws ParseException {//TODO search should not call different url but only add params + Pair> result = extractNamesAndCreateClientSearchBean(request); + return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), + result.getRight().getRight(), null); + } - @RequestMapping(method = RequestMethod.POST, value = "/search", produces = {MediaType.APPLICATION_JSON_VALUE}) - public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params - Pair> result = extractNamesAndCreateClientSearchBean(jsonRequestBody); - return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); + @RequestMapping(method = RequestMethod.POST, value = "/search", produces = { MediaType.APPLICATION_JSON_VALUE }) + public List searchByPost(@RequestBody String jsonRequestBody) + throws ParseException {//TODO search should not call different url but only add params + Pair> result = extractNamesAndCreateClientSearchBean( + jsonRequestBody); + return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), + result.getRight().getRight(), null); - } + } - @RequestMapping(method = RequestMethod.GET, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - public List searchPathByGet(HttpServletRequest request) throws ParseException { + @RequestMapping(method = RequestMethod.GET, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) + public List searchPathByGet(HttpServletRequest request) throws ParseException { - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); - SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); - SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(request); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(request); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(request); - return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); - } + return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); + } - @RequestMapping(method = RequestMethod.POST, value = "/path", produces = {MediaType.APPLICATION_JSON_VALUE}) - public List searchPathByPost(@RequestBody String jsonRequestBody) throws ParseException { + @RequestMapping(method = RequestMethod.POST, value = "/path", produces = { MediaType.APPLICATION_JSON_VALUE }) + public List searchPathByPost(@RequestBody String jsonRequestBody) throws ParseException { - JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); + JSONObject jsonRequestBodyObject = new JSONObject(jsonRequestBody); - String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); - SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); - SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); + String contactPhoneNumber = SearchHelper.getContactPhoneNumberParam(jsonRequestBodyObject); + SearchEntityWrapper childSearchEntity = SearchHelper.childSearchParamProcessor(jsonRequestBodyObject); + SearchEntityWrapper motherSearchEntity = SearchHelper.motherSearchParamProcessor(jsonRequestBodyObject); - return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); + return searchAndProcess(childSearchEntity, motherSearchEntity, contactPhoneNumber); - } + } - private List searchAndProcess(SearchEntityWrapper childSearchEntity, SearchEntityWrapper motherSearchEntity, - String contactPhoneNumber) { - try { - //Process clients search via demographics + private List searchAndProcess(SearchEntityWrapper childSearchEntity, SearchEntityWrapper motherSearchEntity, + String contactPhoneNumber) { + try { + //Process clients search via demographics + + ClientSearchBean searchBean = new ClientSearchBean(); + List children = new ArrayList(); + if (childSearchEntity.isValid()) { + searchBean = childSearchEntity.getClientSearchBean(); + children = searchService + .searchGlobalClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), + searchBean.getLastName(), childSearchEntity.getLimit()); + } + + //Process mothers search via mother demographics + + ClientSearchBean motherSearchBean = new ClientSearchBean(); + List mothers = new ArrayList(); + + if (motherSearchEntity.isValid()) { + motherSearchBean = motherSearchEntity.getClientSearchBean(); + mothers = searchService.searchGlobalClient(motherSearchBean, motherSearchBean.getFirstName(), + motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); + } + + //Process clients search via contact phone number + + List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); + + List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); + + children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection + + List linkedMothers = new ArrayList(); + + String RELATIONSHIP_KEY = "mother"; + if (!children.isEmpty()) { + List clientIds = new ArrayList(); + for (Client c : children) { + String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); + if (relationshipId != null && !clientIds.contains(relationshipId)) { + clientIds.add(relationshipId); + } + } + + linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); + + } + + List linkedChildren = new ArrayList(); + + if (!mothers.isEmpty()) { + for (Client client : mothers) { + linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); + } + } + + children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection + + for (Client linkedMother : linkedMothers) { + if (!SearchHelper.contains(mothers, linkedMother)) { + mothers.add(linkedMother); + } + } - ClientSearchBean searchBean = new ClientSearchBean(); - List children = new ArrayList(); - if (childSearchEntity.isValid()) { - searchBean = childSearchEntity.getClientSearchBean(); - children = searchService.searchGlobalClient(searchBean, searchBean.getFirstName(), searchBean.getMiddleName(), - searchBean.getLastName(), childSearchEntity.getLimit()); - } + return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); - //Process mothers search via mother demographics + } + catch (Exception e) { - ClientSearchBean motherSearchBean = new ClientSearchBean(); - List mothers = new ArrayList(); + logger.error("", e); + return new ArrayList(); + } + } - if (motherSearchEntity.isValid()) { - motherSearchBean = motherSearchEntity.getClientSearchBean(); - mothers = searchService.searchGlobalClient(motherSearchBean, motherSearchBean.getFirstName(), - motherSearchBean.getMiddleName(), motherSearchBean.getLastName(), motherSearchEntity.getLimit()); - } + public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuardianPhoneNumber) { + List clientBaseEntityIds = new ArrayList(); + + if (!StringUtils.isBlank(motherGuardianPhoneNumber)) { - //Process clients search via contact phone number - - - List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); - - List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); - - children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection - - List linkedMothers = new ArrayList(); - - String RELATIONSHIP_KEY = "mother"; - if (!children.isEmpty()) { - List clientIds = new ArrayList(); - for (Client c : children) { - String relationshipId = SearchHelper.getRelationalId(c, RELATIONSHIP_KEY); - if (relationshipId != null && !clientIds.contains(relationshipId)) { - clientIds.add(relationshipId); - } - } - - linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); - - } - - List linkedChildren = new ArrayList(); - - if (!mothers.isEmpty()) { - for (Client client : mothers) { - linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); - } - } - - children = SearchHelper.intersection(children, linkedChildren);// Search conjunction is "AND" find intersection - - for (Client linkedMother : linkedMothers) { - if (!SearchHelper.contains(mothers, linkedMother)) { - mothers.add(linkedMother); - } - } - - return SearchHelper.processSearchResult(children, mothers, RELATIONSHIP_KEY); - - } catch (Exception e) { - - logger.error("", e); - return new ArrayList(); - } - } - - public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuardianPhoneNumber) { - List clientBaseEntityIds = new ArrayList(); - - if (!StringUtils.isBlank(motherGuardianPhoneNumber)) { - - List events = eventService.findEventsByConceptAndValue("159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", - motherGuardianPhoneNumber); - if (events != null && !events.isEmpty()) { - for (Event event : events) { - String entityId = event.getBaseEntityId(); - if (entityId != null && !clientBaseEntityIds.contains(entityId)) { - clientBaseEntityIds.add(entityId); - } - } - - } - } - return clientBaseEntityIds; - } - - public Pair> extractNamesAndCreateClientSearchBean(Object object) throws ParseException { - - String firstName; - String middleName; - String lastName; - String name; - String gender; - String attributes; - String identifiers; - Optional phoneNumber; - Optional altPhoneNumber; - Optional alternateName; - DateTime[] birthdate; - DateTime[] lastEdit; - - ClientSearchBean searchBean = new ClientSearchBean(); - - if(object instanceof HttpServletRequest){ - HttpServletRequest request = (HttpServletRequest) object; - firstName = getStringFilter(FIRST_NAME, request); - middleName = getStringFilter(MIDDLE_NAME, request); - lastName = getStringFilter(LAST_NAME, request); - - phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); - altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); - alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); - - name = getStringFilter(NAME, request); - gender = getStringFilter(GENDER, request); - - birthdate = getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - lastEdit = getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - attributes = getStringFilter(ATTRIBUTE, request); - identifiers = getStringFilter(IDENTIFIER, request); - - } else { - JSONObject jsonObject = new JSONObject((String) object); - - firstName = getStringFilter(FIRST_NAME, jsonObject); - middleName = getStringFilter(MIDDLE_NAME, jsonObject); - lastName = getStringFilter(LAST_NAME, jsonObject); - - phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, jsonObject)); - altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, jsonObject)); - alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, jsonObject)); - - - name = getStringFilter(NAME, jsonObject); - gender = getStringFilter(GENDER, jsonObject); - - birthdate = getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - lastEdit = getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - - attributes = getStringFilter(ATTRIBUTE, jsonObject); - identifiers = getStringFilter(IDENTIFIER, jsonObject); - - } - - searchBean.setNameLike(name); - searchBean.setGender(gender); - - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - Map attributeMap = new HashMap<>(); - - if (!StringUtils.isBlank(attributes)) { - String[] attributeParts = attributes.split(":", -1); - if (attributeParts.length == 2) { - attributeMap.put(attributeParts[0], attributeParts[1]); // put attributeType and attributeValue as key value pair - } - } - - phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); - altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); - alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); - - searchBean.setAttributes(attributeMap); - - Map identifierMap = new HashMap<>(); - if (!StringUtils.isBlank(identifiers)) { - String[] identifierParts = identifiers.split(":", -1); - if (identifierParts.length == 2) { - identifierMap.put(identifierParts[0], identifierParts[1]); // put identifierType and identifierValue key value pair - } - } - - searchBean.setIdentifiers(identifierMap); - - return Pair.of(searchBean, Triple.of(firstName, lastName, middleName)); - } - @Override - public List filter(String query) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client getByUniqueId(String uniqueId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List requiredProperties() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client create(Client entity) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Client update(Client entity) { - // TODO Auto-generated method stub - return null; - } + List events = eventService.findEventsByConceptAndValue("159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + motherGuardianPhoneNumber); + if (events != null && !events.isEmpty()) { + for (Event event : events) { + String entityId = event.getBaseEntityId(); + if (entityId != null && !clientBaseEntityIds.contains(entityId)) { + clientBaseEntityIds.add(entityId); + } + } + + } + } + return clientBaseEntityIds; + } + + public Pair> extractNamesAndCreateClientSearchBean(Object object) + throws ParseException { + + String firstName; + String middleName; + String lastName; + String name; + String gender; + String attributes; + String identifiers; + Optional phoneNumber; + Optional altPhoneNumber; + Optional alternateName; + DateTime[] birthdate; + DateTime[] lastEdit; + + ClientSearchBean searchBean = new ClientSearchBean(); + + if (object instanceof HttpServletRequest) { + HttpServletRequest request = (HttpServletRequest) object; + firstName = getStringFilter(FIRST_NAME, request); + middleName = getStringFilter(MIDDLE_NAME, request); + lastName = getStringFilter(LAST_NAME, request); + + phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, request)); + altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, request)); + alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, request)); + + name = getStringFilter(NAME, request); + gender = getStringFilter(GENDER, request); + + birthdate = getDateRangeFilter(BIRTH_DATE, + request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + attributes = getStringFilter(ATTRIBUTE, request); + identifiers = getStringFilter(IDENTIFIER, request); + + } else { + JSONObject jsonObject = new JSONObject((String) object); + + firstName = getStringFilter(FIRST_NAME, jsonObject); + middleName = getStringFilter(MIDDLE_NAME, jsonObject); + lastName = getStringFilter(LAST_NAME, jsonObject); + + phoneNumber = Optional.ofNullable(getStringFilter(PHONE_NUMBER, jsonObject)); + altPhoneNumber = Optional.ofNullable(getStringFilter(ALT_PHONE_NUMBER, jsonObject)); + alternateName = Optional.ofNullable(getStringFilter(ALT_NAME, jsonObject)); + + name = getStringFilter(NAME, jsonObject); + gender = getStringFilter(GENDER, jsonObject); + + birthdate = getDateRangeFilter(BIRTH_DATE, + jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + lastEdit = getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + + attributes = getStringFilter(ATTRIBUTE, jsonObject); + identifiers = getStringFilter(IDENTIFIER, jsonObject); + + } + + searchBean.setNameLike(name); + searchBean.setGender(gender); + + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + Map attributeMap = new HashMap<>(); + + if (!StringUtils.isBlank(attributes)) { + String[] attributeParts = attributes.split(":", -1); + if (attributeParts.length == 2) { + attributeMap + .put(attributeParts[0], attributeParts[1]); // put attributeType and attributeValue as key value pair + } + } + + phoneNumber.ifPresent(phoneValue -> attributeMap.put(PHONE_NUMBER, phoneValue)); + altPhoneNumber.ifPresent(altPhoneValue -> attributeMap.put(ALT_PHONE_NUMBER, altPhoneValue)); + alternateName.ifPresent(altNameValue -> attributeMap.put(ALT_NAME, altNameValue)); + + searchBean.setAttributes(attributeMap); + + Map identifierMap = new HashMap<>(); + if (!StringUtils.isBlank(identifiers)) { + String[] identifierParts = identifiers.split(":", -1); + if (identifierParts.length == 2) { + identifierMap.put(identifierParts[0], + identifierParts[1]); // put identifierType and identifierValue key value pair + } + } + + searchBean.setIdentifiers(identifierMap); + + return Pair.of(searchBean, Triple.of(firstName, lastName, middleName)); + } + + @Override + public List filter(String query) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client getByUniqueId(String uniqueId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List requiredProperties() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client create(Client entity) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Client update(Client entity) { + // TODO Auto-generated method stub + return null; + } } diff --git a/src/main/java/org/opensrp/web/rest/TaskResource.java b/src/main/java/org/opensrp/web/rest/TaskResource.java index 662f2075e..ddd4bb7b5 100644 --- a/src/main/java/org/opensrp/web/rest/TaskResource.java +++ b/src/main/java/org/opensrp/web/rest/TaskResource.java @@ -67,47 +67,47 @@ @Validated @RequestMapping(value = "/rest/task") public class TaskResource { - + private static Logger logger = LogManager.getLogger(TaskResource.class.toString()); - + public Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new TaskDateTimeTypeConverter()) - .registerTypeAdapter(TaskPriority.class, new PriorityOrdinalConverter()).create(); - + .registerTypeAdapter(TaskPriority.class, new PriorityOrdinalConverter()).create(); + public static final String PLAN = "plan"; - + public static final String GROUP = "group"; - + public static final String OWNER = "owner"; - + private TaskService taskService; - + @Autowired public void setTaskService(TaskService taskService) { this.taskService = taskService; } - + /** * @param gson the gson to set */ public void setGson(Gson gson) { this.gson = gson; } - + @RequestMapping(value = "/{identifier}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getByUniqueId(@PathVariable("identifier") String identifier) { return new ResponseEntity<>(gson.toJson(convertToDTO(taskService.getTask(identifier))), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); } - + @RequestMapping(value = "/sync", method = RequestMethod.POST, consumes = { - MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) + MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getTasksByTaskAndGroup(@RequestBody TaskSyncRequestWrapper taskSyncRequestWrapper) { String plan = StringUtils.join(taskSyncRequestWrapper.getPlan(), ","); String group = StringUtils.join(taskSyncRequestWrapper.getGroup(), ","); String owner = taskSyncRequestWrapper.getOwner(); long serverVersion = taskSyncRequestWrapper.getServerVersion(); boolean returnCount = taskSyncRequestWrapper.isReturnCount(); - + long currentServerVersion = 0; try { currentServerVersion = serverVersion; @@ -117,7 +117,7 @@ public ResponseEntity getTasksByTaskAndGroup(@RequestBody TaskSyncReques } return getTaskSyncResponse(plan, group, owner, currentServerVersion, returnCount); } - + // here for backward compatibility @RequestMapping(value = "/sync", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getTasksByTaskAndGroupTwo(HttpServletRequest request) { @@ -126,7 +126,7 @@ public ResponseEntity getTasksByTaskAndGroupTwo(HttpServletRequest reque String serverVersion = getStringFilter(BaseEntity.SERVER_VERSIOIN, request); String owner = getStringFilter(OWNER, request); boolean returnCount = Boolean.getBoolean(getStringFilter(RETURN_COUNT, request)); - + long currentServerVersion = 0; try { currentServerVersion = Long.parseLong(serverVersion); @@ -136,14 +136,14 @@ public ResponseEntity getTasksByTaskAndGroupTwo(HttpServletRequest reque } return getTaskSyncResponse(plan, group, owner, currentServerVersion, returnCount); } - + private ResponseEntity getTaskSyncResponse(String plan, String group, String owner, long currentServerVersion, - boolean returnCount) { + boolean returnCount) { if (StringUtils.isBlank(plan)) { logger.error("Plan Identifier is missing"); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - + if (!StringUtils.isBlank(group)) { String tasks = gson.toJson(convertToDTO(taskService.getTasksByTaskAndGroup(plan, group, currentServerVersion))); HttpHeaders headers = RestUtils.getJSONUTF8Headers(); @@ -151,7 +151,7 @@ private ResponseEntity getTaskSyncResponse(String plan, String group, St Long taskCount = taskService.countTasksByPlanAndGroup(plan, group, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(taskCount)); } - + return new ResponseEntity<>(tasks, headers, HttpStatus.OK); } else if (!StringUtils.isBlank(owner)) { String tasks = gson.toJson(convertToDTO(taskService.getTasksByPlanAndOwner(plan, owner, currentServerVersion))); @@ -160,14 +160,14 @@ private ResponseEntity getTaskSyncResponse(String plan, String group, St Long taskCount = taskService.countTasksByPlanAndOwner(plan, owner, currentServerVersion); headers.add(TOTAL_RECORDS, String.valueOf(taskCount)); } - + return new ResponseEntity<>(tasks, headers, HttpStatus.OK); } else { logger.error("Either owner or group identifier field is missing"); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } - + @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity create(@RequestBody String entity) { try { @@ -179,9 +179,9 @@ public ResponseEntity create(@RequestBody String entity) { logger.error("The request doesnt contain a valid task representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - + } - + @RequestMapping(method = RequestMethod.PUT, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity update(@RequestBody String entity) { try { @@ -193,34 +193,38 @@ public ResponseEntity update(@RequestBody String entity) { logger.error("The request doesnt contain a valid task representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - + } - + @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, - MediaType.TEXT_PLAIN_VALUE }) + MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity batchSave(@RequestBody String entity) { try { - Type listType = new TypeToken>() {}.getType(); + Type listType = new TypeToken>() { + + }.getType(); List tasks = gson.fromJson(entity, listType); Set tasksWithErrors = taskService.saveTasks(convertToDomain(tasks)); if (tasksWithErrors.isEmpty()) return new ResponseEntity<>("All Tasks processed", HttpStatus.CREATED); else return new ResponseEntity<>("Tasks with identifiers not processed: " + String.join(",", tasksWithErrors), - HttpStatus.CREATED); + HttpStatus.CREATED); } catch (JsonSyntaxException e) { logger.error("The request doesnt contain a valid task representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - + } - + @RequestMapping(value = "/update_status", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, - MediaType.TEXT_PLAIN_VALUE }) + MediaType.TEXT_PLAIN_VALUE }) public ResponseEntity updateStatus(@RequestBody String entity) { try { - Type listType = new TypeToken>() {}.getType(); + Type listType = new TypeToken>() { + + }.getType(); List taskUpdates = gson.fromJson(entity, listType); List updateTasks = taskService.updateTaskStatus(taskUpdates); if (updateTasks.size() > 0) { @@ -235,9 +239,9 @@ public ResponseEntity updateStatus(@RequestBody String entity) { logger.error("The request doesnt contain a valid task update representation", e); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - + } - + /** * This methods provides an API endpoint that searches for all task Ids ordered by server * version ascending @@ -247,34 +251,34 @@ public ResponseEntity updateStatus(@RequestBody String entity) { */ @RequestMapping(value = "/findIds", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity findIds(@RequestParam(value = SERVER_VERSION) long serverVersion, - @RequestParam(value = "fromDate", required = false) String fromDate, - @RequestParam(value = "toDate", required = false) String toDate) { - + @RequestParam(value = "fromDate", required = false) String fromDate, + @RequestParam(value = "toDate", required = false) String toDate) { + Pair, Long> taskIdsPair = taskService.findAllTaskIds(serverVersion, DEFAULT_GET_ALL_IDS_LIMIT, - Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); + Utils.getDateFromString(fromDate), Utils.getDateFromString(toDate)); Identifier identifiers = new Identifier(); identifiers.setIdentifiers(taskIdsPair.getLeft()); identifiers.setLastServerVersion(taskIdsPair.getRight()); return new ResponseEntity<>(identifiers, HttpStatus.OK); } - + /** * Fetch tasks ordered by serverVersion ascending * * @param serverVersion serverVersion using to filter by - * @param limit upper limit on number of tasks to fetch + * @param limit upper limit on number of tasks to fetch * @return A list of tasks */ @RequestMapping(value = "/getAll", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity getAll(@RequestParam(value = SERVER_VERSION) long serverVersion, - @RequestParam(value = LIMIT, required = false) Integer limit) { - + @RequestParam(value = LIMIT, required = false) Integer limit) { + Integer pageLimit = limit == null ? DEFAULT_LIMIT : limit; return new ResponseEntity<>(gson.toJson(convertToDTO(taskService.getAllTasks(serverVersion, pageLimit))), - RestUtils.getJSONUTF8Headers(), HttpStatus.OK); - + RestUtils.getJSONUTF8Headers(), HttpStatus.OK); + } - + /** * Fetch count of tasks * @@ -306,9 +310,10 @@ public ResponseEntity getOptionalTasksWithCount(@Valid TaskSearchBean ta response.put(TOTAL_RECORDS, taskCount); return new ResponseEntity<>(gson.toJson(response), headers, HttpStatus.OK); } - + /** * Converts a Task to DTO object so that data model for V1 API is maintained + * * @param task the task to convert * @return TaskDTO v1 task contract */ @@ -322,32 +327,35 @@ public Task convertToDTO(Task task) { taskDto.setExecutionPeriod(null); return taskDto; } - + /** * Converts a list of Tasks to DTO objects so that data model for V1 API is maintained + * * @param list of tasks to convert * @return list of TaskDTO objects */ public List convertToDTO(List taskList) { return taskList.stream().map(t -> convertToDTO(t)).collect(Collectors.toList()); } - + /** * Converts a TaskDTO to domain object for persistence - * @param the TaskDTO object to convert + * + * @param the TaskDTO object to convert * @return the converted task domain objects */ public Task convertToDomain(TaskDto taskDto) { Task task = new Task(); BeanUtils.copyProperties(taskDto, task); - if(taskDto.getExecutionStartDate()!=null || taskDto.getExecutionEndDate()!=null) { - task.setExecutionPeriod(new Period(taskDto.getExecutionStartDate(),taskDto.getExecutionEndDate())); + if (taskDto.getExecutionStartDate() != null || taskDto.getExecutionEndDate() != null) { + task.setExecutionPeriod(new Period(taskDto.getExecutionStartDate(), taskDto.getExecutionEndDate())); } return task; } - + /** * Converts a list of TaskDTO to domain objects for persistence + * * @param list of TaskDTO objects to convert * @return list of converted task domain objects */ diff --git a/src/main/java/org/opensrp/web/utils/SearchHelper.java b/src/main/java/org/opensrp/web/utils/SearchHelper.java index 2a56779a6..5918b32b0 100644 --- a/src/main/java/org/opensrp/web/utils/SearchHelper.java +++ b/src/main/java/org/opensrp/web/utils/SearchHelper.java @@ -19,405 +19,412 @@ public class SearchHelper { - public static final String ZEIR_ID = "zeir_id"; - public static final String OPENSRP_ID = "opensrp_id"; + public static final String ZEIR_ID = "zeir_id"; - public static final String SIM_PRINT_GUID = "simprints_guid"; + public static final String OPENSRP_ID = "opensrp_id"; - public static final String FIRST_NAME = "first_name"; - public static final String MIDDLE_NAME = "middle_name"; - public static final String LAST_NAME = "last_name"; - public static final String BIRTH_DATE = "birth_date"; + public static final String SIM_PRINT_GUID = "simprints_guid"; - //Attributes - public static final String INACTIVE = "inactive"; - public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; - public static final String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; + public static final String FIRST_NAME = "first_name"; - // Mother - public static final String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; - public static final String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; - public static final String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; - public static final String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; + public static final String MIDDLE_NAME = "middle_name"; - public static final String NRC_NUMBER_KEY = "NRC_Number"; - public static final String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; + public static final String LAST_NAME = "last_name"; - public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { + public static final String BIRTH_DATE = "birth_date"; - ClientSearchBean searchBean = new ClientSearchBean(); + //Attributes + public static final String INACTIVE = "inactive"; + public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; - Integer limit = RestUtils.getIntegerFilter("limit", request); - if (limit == null || limit.intValue() == 0) { - limit = 100; - } + public static final String NFC_CARD_IDENTIFIER = "nfc_card_identifier"; - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } + // Mother + public static final String MOTHER_GUARDIAN_FIRST_NAME = "mother_first_name"; - searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, request)); - searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, request)); - searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, request)); - searchBean.setGender(RestUtils.getStringFilter(GENDER, request)); + public static final String MOTHER_GUARDIAN_LAST_NAME = "mother_last_name"; - DateTime[] birthdate = RestUtils - .getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + public static final String MOTHER_GUARDIAN_NRC_NUMBER = "mother_nrc_number"; - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + public static final String MOTHER_COMPASS_RELATIONSHIP_ID = "mother_compass_relationship_id"; - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } + public static final String NRC_NUMBER_KEY = "NRC_Number"; + public static final String COMPASS_RELATIONSHIP_ID = "Compass_Relationship_ID"; - Map commonSearchParams = new HashMap<>(); - commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, request)); - commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, request)); - commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, request)); - commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, request)); - commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request)); - commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request)); + public static SearchEntityWrapper childSearchParamProcessor(HttpServletRequest request) throws ParseException { - setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); + ClientSearchBean searchBean = new ClientSearchBean(); - boolean isValid = isSearchValid(searchBean); + Integer limit = RestUtils.getIntegerFilter("limit", request); + if (limit == null || limit.intValue() == 0) { + limit = 100; + } - return new SearchEntityWrapper(isValid, searchBean, limit); - } + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } - public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest request) throws ParseException { + searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, request)); + searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, request)); + searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, request)); + searchBean.setGender(RestUtils.getStringFilter(GENDER, request)); - ClientSearchBean motherSearchBean = new ClientSearchBean(); + DateTime[] birthdate = RestUtils + .getDateRangeFilter(BIRTH_DATE, request);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - Integer limit = setCoreFilters(request, motherSearchBean); + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } - String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, request); - String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, request); + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, request)); + commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, request)); + commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, request)); + commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, request)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, request)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, request)); - motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, request)); - motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, request)); + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); - setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); + boolean isValid = isSearchValid(searchBean); - boolean isValid = isSearchValid(motherSearchBean); + return new SearchEntityWrapper(isValid, searchBean, limit); + } - return new SearchEntityWrapper(isValid, motherSearchBean, limit); - } + public static SearchEntityWrapper motherSearchParamProcessor(HttpServletRequest request) throws ParseException { - public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObject) throws ParseException { + ClientSearchBean motherSearchBean = new ClientSearchBean(); - ClientSearchBean searchBean = new ClientSearchBean(); + Integer limit = setCoreFilters(request, motherSearchBean); - Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) - : jsonObject.optInt("limit"); - if (limit == 0) { - limit = 100; - } + String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, request); + String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, request); - DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } + motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, request)); + motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, request)); - searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, jsonObject)); - searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, jsonObject)); - searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, jsonObject)); - searchBean.setGender(RestUtils.getStringFilter(GENDER, jsonObject)); + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); - DateTime[] birthdate = RestUtils - .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html + boolean isValid = isSearchValid(motherSearchBean); - //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } - if (birthdate != null) { - searchBean.setBirthdateFrom(birthdate[0]); - searchBean.setBirthdateTo(birthdate[1]); - } + public static SearchEntityWrapper childSearchParamProcessor(JSONObject jsonObject) throws ParseException { - Map commonSearchParams = new HashMap<>(); - commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, jsonObject)); - commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, jsonObject)); - commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, jsonObject)); - commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, jsonObject)); - commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, jsonObject)); - commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, jsonObject)); + ClientSearchBean searchBean = new ClientSearchBean(); - setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); + Integer limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + if (limit == 0) { + limit = 100; + } - boolean isValid = isSearchValid(searchBean); + DateTime[] lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } - return new SearchEntityWrapper(isValid, searchBean, limit); - } + searchBean.setFirstName(RestUtils.getStringFilter(FIRST_NAME, jsonObject)); + searchBean.setMiddleName(RestUtils.getStringFilter(MIDDLE_NAME, jsonObject)); + searchBean.setLastName(RestUtils.getStringFilter(LAST_NAME, jsonObject)); + searchBean.setGender(RestUtils.getStringFilter(GENDER, jsonObject)); - public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObject) throws ParseException { + DateTime[] birthdate = RestUtils + .getDateRangeFilter(BIRTH_DATE, jsonObject);//TODO add ranges like fhir do http://hl7.org/fhir/search.html - ClientSearchBean motherSearchBean = new ClientSearchBean(); + //TODO lookinto Swagger https://slack-files.com/files-pri-safe/T0EPSEJE9-F0TBD0N77/integratingswagger.pdf?c=1458211183-179d2bfd2e974585c5038fba15a86bf83097810a - Integer limit = setCoreFilters(jsonObject, motherSearchBean); + if (birthdate != null) { + searchBean.setBirthdateFrom(birthdate[0]); + searchBean.setBirthdateTo(birthdate[1]); + } - String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, jsonObject); - String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, jsonObject); + Map commonSearchParams = new HashMap<>(); + commonSearchParams.put(ZEIR_ID, RestUtils.getStringFilter(ZEIR_ID, jsonObject)); + commonSearchParams.put(OPENSRP_ID, RestUtils.getStringFilter(OPENSRP_ID, jsonObject)); + commonSearchParams.put(SIM_PRINT_GUID, RestUtils.getStringFilter(SIM_PRINT_GUID, jsonObject)); + commonSearchParams.put(INACTIVE, RestUtils.getStringFilter(INACTIVE, jsonObject)); + commonSearchParams.put(LOST_TO_FOLLOW_UP, RestUtils.getStringFilter(LOST_TO_FOLLOW_UP, jsonObject)); + commonSearchParams.put(NFC_CARD_IDENTIFIER, RestUtils.getStringFilter(NFC_CARD_IDENTIFIER, jsonObject)); - motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, jsonObject)); - motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, jsonObject)); + setIdentifiersAndAttributeToChildSearchBean(commonSearchParams, searchBean); - setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); + boolean isValid = isSearchValid(searchBean); - boolean isValid = isSearchValid(motherSearchBean); + return new SearchEntityWrapper(isValid, searchBean, limit); + } - return new SearchEntityWrapper(isValid, motherSearchBean, limit); - } + public static SearchEntityWrapper motherSearchParamProcessor(JSONObject jsonObject) throws ParseException { - public static void setNameLikeAndAtrributesOnMotherSearchBean(String motherGuardianNrc, - String compassRelationshipId, - ClientSearchBean motherSearchBean) { - Map motherAttributes = new HashMap<>(); - if (!StringUtils.isBlank(motherGuardianNrc)) { - motherAttributes.put(NRC_NUMBER_KEY, motherGuardianNrc); - } - if (!StringUtils.isBlank(compassRelationshipId)) { - motherAttributes.put(COMPASS_RELATIONSHIP_ID, compassRelationshipId); - } + ClientSearchBean motherSearchBean = new ClientSearchBean(); - String nameLike = null; + Integer limit = setCoreFilters(jsonObject, motherSearchBean); - if (!StringUtils.isBlank(motherSearchBean.getFirstName()) - && StringUtils.containsWhitespace(motherSearchBean.getFirstName().trim()) - && StringUtils.isBlank(motherSearchBean.getLastName())) { - String[] arr = motherSearchBean.getFirstName().split("\\s+"); - nameLike = arr[0]; - motherSearchBean.setFirstName(null); - } + String motherGuardianNrc = RestUtils.getStringFilter(MOTHER_GUARDIAN_NRC_NUMBER, jsonObject); + String compassRelationshipId = RestUtils.getStringFilter(MOTHER_COMPASS_RELATIONSHIP_ID, jsonObject); - motherSearchBean.setNameLike(nameLike); - motherSearchBean.setAttributes(motherAttributes); + motherSearchBean.setFirstName(RestUtils.getStringFilter(MOTHER_GUARDIAN_FIRST_NAME, jsonObject)); + motherSearchBean.setLastName(RestUtils.getStringFilter(MOTHER_GUARDIAN_LAST_NAME, jsonObject)); - } + setNameLikeAndAtrributesOnMotherSearchBean(motherGuardianNrc, compassRelationshipId, motherSearchBean); - public static void setIdentifiersAndAttributeToChildSearchBean(Map commonSearchParams, ClientSearchBean searchBean) { - Map identifiers = new HashMap(); + boolean isValid = isSearchValid(motherSearchBean); - String zeirId = commonSearchParams.get(ZEIR_ID); - String opensrpId = commonSearchParams.get(OPENSRP_ID); - String simprintsGuid = commonSearchParams.get(SIM_PRINT_GUID); - String lostToFollowUp = commonSearchParams.get(LOST_TO_FOLLOW_UP); - String inActive = commonSearchParams.get(INACTIVE); - String nfcCardIdentifier = commonSearchParams.get(NFC_CARD_IDENTIFIER); + return new SearchEntityWrapper(isValid, motherSearchBean, limit); + } - if (!StringUtils.isBlank(zeirId)) { - identifiers.put(ZEIR_ID, zeirId); - identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key - } + public static void setNameLikeAndAtrributesOnMotherSearchBean(String motherGuardianNrc, + String compassRelationshipId, + ClientSearchBean motherSearchBean) { + Map motherAttributes = new HashMap<>(); + if (!StringUtils.isBlank(motherGuardianNrc)) { + motherAttributes.put(NRC_NUMBER_KEY, motherGuardianNrc); + } + if (!StringUtils.isBlank(compassRelationshipId)) { + motherAttributes.put(COMPASS_RELATIONSHIP_ID, compassRelationshipId); + } - if (!StringUtils.isBlank(opensrpId)) { - identifiers.put(OPENSRP_ID, opensrpId); - } - if (!StringUtils.isBlank(simprintsGuid)) { - identifiers.put(SIM_PRINT_GUID, simprintsGuid); - } + String nameLike = null; - Map attributes = new HashMap(); - if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) - || !StringUtils.isBlank(nfcCardIdentifier)) { + if (!StringUtils.isBlank(motherSearchBean.getFirstName()) + && StringUtils.containsWhitespace(motherSearchBean.getFirstName().trim()) + && StringUtils.isBlank(motherSearchBean.getLastName())) { + String[] arr = motherSearchBean.getFirstName().split("\\s+"); + nameLike = arr[0]; + motherSearchBean.setFirstName(null); + } - if (!StringUtils.isBlank(inActive)) { - attributes.put(INACTIVE, inActive); - } + motherSearchBean.setNameLike(nameLike); + motherSearchBean.setAttributes(motherAttributes); - if (!StringUtils.isBlank(lostToFollowUp)) { - attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); - } + } - if (!StringUtils.isBlank(nfcCardIdentifier)) { - attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant - } - } + public static void setIdentifiersAndAttributeToChildSearchBean(Map commonSearchParams, + ClientSearchBean searchBean) { + Map identifiers = new HashMap(); - searchBean.setIdentifiers(identifiers); - searchBean.setAttributes(attributes); + String zeirId = commonSearchParams.get(ZEIR_ID); + String opensrpId = commonSearchParams.get(OPENSRP_ID); + String simprintsGuid = commonSearchParams.get(SIM_PRINT_GUID); + String lostToFollowUp = commonSearchParams.get(LOST_TO_FOLLOW_UP); + String inActive = commonSearchParams.get(INACTIVE); + String nfcCardIdentifier = commonSearchParams.get(NFC_CARD_IDENTIFIER); + + if (!StringUtils.isBlank(zeirId)) { + identifiers.put(ZEIR_ID, zeirId); + identifiers.put("ZEIR_ID", zeirId); //Maintains backward compatibility with upper case key + } + + if (!StringUtils.isBlank(opensrpId)) { + identifiers.put(OPENSRP_ID, opensrpId); + } + if (!StringUtils.isBlank(simprintsGuid)) { + identifiers.put(SIM_PRINT_GUID, simprintsGuid); + } - } + Map attributes = new HashMap(); + if (!StringUtils.isBlank(inActive) || !StringUtils.isBlank(lostToFollowUp) + || !StringUtils.isBlank(nfcCardIdentifier)) { - public static Integer setCoreFilters(Object object, ClientSearchBean searchBean) throws ParseException { + if (!StringUtils.isBlank(inActive)) { + attributes.put(INACTIVE, inActive); + } - Integer limit = 0; - DateTime[] lastEdit = null; + if (!StringUtils.isBlank(lostToFollowUp)) { + attributes.put(LOST_TO_FOLLOW_UP, lostToFollowUp); + } + if (!StringUtils.isBlank(nfcCardIdentifier)) { + attributes.put("NFC_Card_Identifier", nfcCardIdentifier);//Key different case than constant + } + } - if( object instanceof HttpServletRequest ){ - HttpServletRequest request = (HttpServletRequest) object; - lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id - limit = RestUtils.getIntegerFilter("limit", request); - } + searchBean.setIdentifiers(identifiers); + searchBean.setAttributes(attributes); - if( object instanceof JSONObject ){ - JSONObject jsonObject = (JSONObject) object; - lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id - limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) - : jsonObject.optInt("limit"); - } + } - if (limit == null || limit == 0) { - limit = 100; - } - - if (lastEdit != null) { - searchBean.setLastEditFrom(lastEdit[0]); - searchBean.setLastEditTo(lastEdit[1]); - } - - return limit; - - } - - /** - * Here we check to see if the search entity param is valid for use in child search Some form of - * reflections and custom annotations might have been better - * - * @param searchBean model with search params - * @return boolean whether the search entity is valid - */ - - public static boolean isSearchValid(ClientSearchBean searchBean) { - - return !StringUtils.isBlank(searchBean.getFirstName()) - || !StringUtils.isBlank(searchBean.getMiddleName()) - || !StringUtils.isBlank(searchBean.getLastName()) - || !StringUtils.isBlank(searchBean.getGender()) - || (searchBean.getAttributes() != null && !searchBean.getAttributes().isEmpty()) - || searchBean.getBirthdateFrom() != null || searchBean.getBirthdateTo() != null - || searchBean.getLastEditFrom() != null || searchBean.getLastEditTo() != null - || (searchBean.getIdentifiers() != null && !searchBean.getIdentifiers().isEmpty()) - || !StringUtils.isBlank(searchBean.getNameLike()); - - } - - /** - * // Method returns the intersection of two lists - * - * @param list1_ - * @param list2_ - * @return merged intersection list - */ - public static List intersection(List list1_, List list2_) { - - List list1 = list1_; - List list2 = list2_; - - list1 = createClientListIfEmpty(list1); - - list2 = createClientListIfEmpty(list2); - - if (list1.isEmpty() && list2.isEmpty()) { - return new ArrayList(); - } - - if (list1.isEmpty() && !list2.isEmpty()) { - return list2; - } - - if (list2.isEmpty() && !list1.isEmpty()) { - return list1; - } - - List list = new ArrayList(); - - for (Client t : list1) { - if (contains(list2, t)) { - list.add(t); - } - } - - return list; - } - - public static List createClientListIfEmpty(List list_) { - List list = list_; - - if (list == null) { - list = new ArrayList(); - } - - return list; - } - - public static boolean contains(List clients, Client c) { - if (clients == null || clients.isEmpty() || c == null || c.getBaseEntityId() == null) { - return false; - } - for (Client client : clients) { - - if (client != null && client.getBaseEntityId() != null - && c.getBaseEntityId().equals(client.getBaseEntityId())) { - - return true; - - } - } - return false; - } - - public static String getContactPhoneNumberParam(HttpServletRequest request) { - //Search by mother contact number - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; - String motherGuardianPhoneNumber = RestUtils.getStringFilter(MOTHER_GUARDIAN_PHONE_NUMBER, request); - motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) - ? RestUtils.getStringFilter(CONTACT_PHONE_NUMBER, request) - : motherGuardianPhoneNumber; - - return motherGuardianPhoneNumber; - } - - public static String getContactPhoneNumberParam(JSONObject jsonObject) { - //Search by mother contact number - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; - String motherGuardianPhoneNumber = jsonObject.optString(MOTHER_GUARDIAN_PHONE_NUMBER); - motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) - ? jsonObject.optString(CONTACT_PHONE_NUMBER) - : motherGuardianPhoneNumber; - - return motherGuardianPhoneNumber; - } - - public static List processSearchResult(List children, List mothers, - String RELATIONSHIP_KEY) { - List childMotherList = new ArrayList(); - for (Client child : children) { - for (Client mother : mothers) { - String relationalId = getRelationalId(child, RELATIONSHIP_KEY); - String motherEntityId = mother.getBaseEntityId(); - if (relationalId != null && relationalId.equalsIgnoreCase(motherEntityId)) { - childMotherList.add(new ChildMother(child, mother)); - } - } - } - - return childMotherList; - } - - public static String getRelationalId(Client c, String relationshipKey) { - Map> relationships = c.getRelationships(); - if (relationships != null) { - for (Map.Entry> entry : relationships.entrySet()) { - String key = entry.getKey(); - if (key.equalsIgnoreCase(relationshipKey)) { - List rList = entry.getValue(); - if (!rList.isEmpty()) { - return rList.get(0); - } - } - } - } - - return null; - } + public static Integer setCoreFilters(Object object, ClientSearchBean searchBean) throws ParseException { + + Integer limit = 0; + DateTime[] lastEdit = null; + + if (object instanceof HttpServletRequest) { + HttpServletRequest request = (HttpServletRequest) object; + lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, request);//TODO client by provider id + limit = RestUtils.getIntegerFilter("limit", request); + } + + if (object instanceof JSONObject) { + JSONObject jsonObject = (JSONObject) object; + lastEdit = RestUtils.getDateRangeFilter(LAST_UPDATE, jsonObject);//TODO client by provider id + limit = !jsonObject.optString("limit").equals("") ? Integer.parseInt(jsonObject.optString("limit")) + : jsonObject.optInt("limit"); + } + + if (limit == null || limit == 0) { + limit = 100; + } + + if (lastEdit != null) { + searchBean.setLastEditFrom(lastEdit[0]); + searchBean.setLastEditTo(lastEdit[1]); + } + + return limit; + + } + + /** + * Here we check to see if the search entity param is valid for use in child search Some form of + * reflections and custom annotations might have been better + * + * @param searchBean model with search params + * @return boolean whether the search entity is valid + */ + + public static boolean isSearchValid(ClientSearchBean searchBean) { + + return !StringUtils.isBlank(searchBean.getFirstName()) + || !StringUtils.isBlank(searchBean.getMiddleName()) + || !StringUtils.isBlank(searchBean.getLastName()) + || !StringUtils.isBlank(searchBean.getGender()) + || (searchBean.getAttributes() != null && !searchBean.getAttributes().isEmpty()) + || searchBean.getBirthdateFrom() != null || searchBean.getBirthdateTo() != null + || searchBean.getLastEditFrom() != null || searchBean.getLastEditTo() != null + || (searchBean.getIdentifiers() != null && !searchBean.getIdentifiers().isEmpty()) + || !StringUtils.isBlank(searchBean.getNameLike()); + + } + + /** + * // Method returns the intersection of two lists + * + * @param list1_ + * @param list2_ + * @return merged intersection list + */ + public static List intersection(List list1_, List list2_) { + + List list1 = list1_; + List list2 = list2_; + + list1 = createClientListIfEmpty(list1); + + list2 = createClientListIfEmpty(list2); + + if (list1.isEmpty() && list2.isEmpty()) { + return new ArrayList(); + } + + if (list1.isEmpty() && !list2.isEmpty()) { + return list2; + } + + if (list2.isEmpty() && !list1.isEmpty()) { + return list1; + } + + List list = new ArrayList(); + + for (Client t : list1) { + if (contains(list2, t)) { + list.add(t); + } + } + + return list; + } + + public static List createClientListIfEmpty(List list_) { + List list = list_; + + if (list == null) { + list = new ArrayList(); + } + + return list; + } + + public static boolean contains(List clients, Client c) { + if (clients == null || clients.isEmpty() || c == null || c.getBaseEntityId() == null) { + return false; + } + for (Client client : clients) { + + if (client != null && client.getBaseEntityId() != null + && c.getBaseEntityId().equals(client.getBaseEntityId())) { + + return true; + + } + } + return false; + } + + public static String getContactPhoneNumberParam(HttpServletRequest request) { + //Search by mother contact number + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String motherGuardianPhoneNumber = RestUtils.getStringFilter(MOTHER_GUARDIAN_PHONE_NUMBER, request); + motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) + ? RestUtils.getStringFilter(CONTACT_PHONE_NUMBER, request) + : motherGuardianPhoneNumber; + + return motherGuardianPhoneNumber; + } + + public static String getContactPhoneNumberParam(JSONObject jsonObject) { + //Search by mother contact number + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String motherGuardianPhoneNumber = jsonObject.optString(MOTHER_GUARDIAN_PHONE_NUMBER); + motherGuardianPhoneNumber = StringUtils.isBlank(motherGuardianPhoneNumber) + ? jsonObject.optString(CONTACT_PHONE_NUMBER) + : motherGuardianPhoneNumber; + + return motherGuardianPhoneNumber; + } + + public static List processSearchResult(List children, List mothers, + String RELATIONSHIP_KEY) { + List childMotherList = new ArrayList(); + for (Client child : children) { + for (Client mother : mothers) { + String relationalId = getRelationalId(child, RELATIONSHIP_KEY); + String motherEntityId = mother.getBaseEntityId(); + if (relationalId != null && relationalId.equalsIgnoreCase(motherEntityId)) { + childMotherList.add(new ChildMother(child, mother)); + } + } + } + + return childMotherList; + } + + public static String getRelationalId(Client c, String relationshipKey) { + Map> relationships = c.getRelationships(); + if (relationships != null) { + for (Map.Entry> entry : relationships.entrySet()) { + String key = entry.getKey(); + if (key.equalsIgnoreCase(relationshipKey)) { + List rList = entry.getValue(); + if (!rList.isEmpty()) { + return rList.get(0); + } + } + } + } + + return null; + } } diff --git a/src/main/java/org/opensrp/web/utils/Utils.java b/src/main/java/org/opensrp/web/utils/Utils.java index 56f21fa17..5df6b6850 100644 --- a/src/main/java/org/opensrp/web/utils/Utils.java +++ b/src/main/java/org/opensrp/web/utils/Utils.java @@ -1,5 +1,5 @@ /** - * + * */ package org.opensrp.web.utils; @@ -16,7 +16,7 @@ * @author Samuel Githengi created on 06/12/20 */ public class Utils { - + public static String getStringFromJSON(JSONObject jsonObject, String key) { Object value = jsonObject.get(key); if (value instanceof JSONArray) { @@ -28,7 +28,7 @@ public static String getStringFromJSON(JSONObject jsonObject, String key) { public static Date getDateFromString(@Nullable String date) { DateTime dateTime = getDateTimeFromString(date); - if(dateTime != null){ + if (dateTime != null) { return dateTime.toDate(); } return null; @@ -53,7 +53,6 @@ public static DateTime getDateTimeFromString(@Nullable String date) { } } - public static boolean checkRoleIfRoleExists(List roleList, String role) { for (String roleName : roleList) if (StringUtils.containsIgnoreCase(roleName, role)) diff --git a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java index fc1521ba3..bcf8941ec 100755 --- a/src/test/java/org/opensrp/web/rest/SearchResourceTest.java +++ b/src/test/java/org/opensrp/web/rest/SearchResourceTest.java @@ -31,84 +31,86 @@ import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = TestWebContextLoader.class, locations = {"classpath:test-webmvc-config.xml",}) +@ContextConfiguration(loader = TestWebContextLoader.class, locations = { "classpath:test-webmvc-config.xml", }) public class SearchResourceTest { - @Autowired - protected WebApplicationContext webApplicationContext; + @Autowired + protected WebApplicationContext webApplicationContext; - private SearchService searchService; + private SearchService searchService; - private ClientService clientService; + private ClientService clientService; - private EventService eventService; + private EventService eventService; - private ExportEventDataMapper exportEventDataMapper; + private ExportEventDataMapper exportEventDataMapper; - private TaskGenerator taskGenerator; + private TaskGenerator taskGenerator; - private PlanRepository planRepository; + private PlanRepository planRepository; - MockHttpServletRequest mockHttpServletRequest; - String phoneNumber = "0727000000"; - String firstName = "name"; - DateTime birthDate = new DateTime(0l, DateTimeZone.UTC); + MockHttpServletRequest mockHttpServletRequest; + String phoneNumber = "0727000000"; - @Before - public void setUp() { - SearchRepository searchRepository = Mockito.mock(SearchRepository.class); - ClientsRepository clientRepository = Mockito.mock(ClientsRepository.class); - EventsRepository eventsRepository = Mockito.mock(EventsRepository.class); + String firstName = "name"; - searchService = Mockito.spy(new SearchService(searchRepository)); - clientService = Mockito.spy(new ClientService(clientRepository)); - eventService = Mockito.spy( - new EventService(eventsRepository, clientService, taskGenerator, planRepository, exportEventDataMapper)); + DateTime birthDate = new DateTime(0l, DateTimeZone.UTC); - } + @Before + public void setUp() { + SearchRepository searchRepository = Mockito.mock(SearchRepository.class); + ClientsRepository clientRepository = Mockito.mock(ClientsRepository.class); + EventsRepository eventsRepository = Mockito.mock(EventsRepository.class); - @Test - public void testInstantanceCreatesCorrectly() { - SearchResource searchResource = new SearchResource(searchService, clientService, eventService); - Assert.assertNotNull(searchResource); + searchService = Mockito.spy(new SearchService(searchRepository)); + clientService = Mockito.spy(new ClientService(clientRepository)); + eventService = Mockito.spy( + new EventService(eventsRepository, clientService, taskGenerator, planRepository, exportEventDataMapper)); - } + } - @Test - public void testIntersectionMethodReturnsCorrectResult() { - Client clientA = Mockito.mock(Client.class); - List listA = Arrays.asList(new Client[]{clientA}); - List result = SearchHelper.intersection(null, listA); + @Test + public void testInstantanceCreatesCorrectly() { + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + Assert.assertNotNull(searchResource); - Assert.assertNotNull(result); - Assert.assertEquals(listA, result); + } - } + @Test + public void testIntersectionMethodReturnsCorrectResult() { + Client clientA = Mockito.mock(Client.class); + List listA = Arrays.asList(new Client[] { clientA }); + List result = SearchHelper.intersection(null, listA); - @Test - public void shouldSearchClientWithGetRequest() throws ParseException { - mockHttpServletRequest = new MockHttpServletRequest(); - mockHttpServletRequest.addParameter("ff", "ona"); - mockHttpServletRequest.addParameter("phone_number", phoneNumber); - mockHttpServletRequest.addParameter("alt_phone_number", phoneNumber); - mockHttpServletRequest.addParameter("alt_name", firstName); - mockHttpServletRequest.addParameter("attribute", "next_contact_date:2022-06-15"); - mockHttpServletRequest.addParameter("dob", String.valueOf(birthDate)); - mockHttpServletRequest.addParameter("identifier", "fsdf" + ":" + "sfdf"); - SearchResource searchResource = new SearchResource(searchService, clientService, eventService); - List clients = searchResource.search(mockHttpServletRequest); - Assert.assertNotNull(clients); - } + Assert.assertNotNull(result); + Assert.assertEquals(listA, result); - @Test - public void shouldSearchClientWithPostRequest() throws ParseException { - String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + - "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + - "\"attribute\":\"next_contact_date:2022-06-15\"}"; - SearchResource searchResource = new SearchResource(searchService, clientService, eventService); - List clients = searchResource.searchByPost(jsonRequestString); - Assert.assertNotNull(clients); + } - } + @Test + public void shouldSearchClientWithGetRequest() throws ParseException { + mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addParameter("ff", "ona"); + mockHttpServletRequest.addParameter("phone_number", phoneNumber); + mockHttpServletRequest.addParameter("alt_phone_number", phoneNumber); + mockHttpServletRequest.addParameter("alt_name", firstName); + mockHttpServletRequest.addParameter("attribute", "next_contact_date:2022-06-15"); + mockHttpServletRequest.addParameter("dob", String.valueOf(birthDate)); + mockHttpServletRequest.addParameter("identifier", "fsdf" + ":" + "sfdf"); + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + List clients = searchResource.search(mockHttpServletRequest); + Assert.assertNotNull(clients); + } + + @Test + public void shouldSearchClientWithPostRequest() throws ParseException { + String jsonRequestString = "{\"ff\":\"ona\",\"identifier\":\"fsdf:sfdf\",\"alt_name\":\"name\"," + + "\"alt_phone_number\":\"0727000000\",\"dob\":\"1970-01-01T00:00:00.000Z\",\"phone_number\":\"0727000000\"," + + "\"attribute\":\"next_contact_date:2022-06-15\"}"; + SearchResource searchResource = new SearchResource(searchService, clientService, eventService); + List clients = searchResource.searchByPost(jsonRequestString); + Assert.assertNotNull(clients); + + } } diff --git a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java index 21d0b3348..d11f40534 100644 --- a/src/test/java/org/opensrp/web/utils/SearchHelperTest.java +++ b/src/test/java/org/opensrp/web/utils/SearchHelperTest.java @@ -15,363 +15,365 @@ public class SearchHelperTest { - @Test - public void testCreateClientListIfEmptyCreatesListOnNull() { + @Test + public void testCreateClientListIfEmptyCreatesListOnNull() { - List list = SearchHelper.createClientListIfEmpty(null); - Assert.assertNotNull(list); - } + List list = SearchHelper.createClientListIfEmpty(null); + Assert.assertNotNull(list); + } - @Test - public void testCreateClientListIfEmptyDoesNotModifyParameterList() { - Client client = new Client("dummy-base-entity-id"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + @Test + public void testCreateClientListIfEmptyDoesNotModifyParameterList() { + Client client = new Client("dummy-base-entity-id"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - List myClientList = Arrays.asList(new Client[]{client}); + List myClientList = Arrays.asList(new Client[] { client }); - List list = SearchHelper.createClientListIfEmpty(myClientList); + List list = SearchHelper.createClientListIfEmpty(myClientList); - Assert.assertNotNull(list); - org.springframework.util.Assert.notEmpty(list); - Assert.assertEquals("dummy-base-entity-id", list.get(0).getBaseEntityId()); - Assert.assertEquals("Johnny", list.get(0).getFirstName()); - Assert.assertEquals("Test", list.get(0).getLastName()); - Assert.assertEquals("MALE", list.get(0).getGender()); - } + Assert.assertNotNull(list); + org.springframework.util.Assert.notEmpty(list); + Assert.assertEquals("dummy-base-entity-id", list.get(0).getBaseEntityId()); + Assert.assertEquals("Johnny", list.get(0).getFirstName()); + Assert.assertEquals("Test", list.get(0).getLastName()); + Assert.assertEquals("MALE", list.get(0).getGender()); + } - @Test - public void testGetContactPhoneNumberParamReturnsCorrectValueForParam() { + @Test + public void testGetContactPhoneNumberParamReturnsCorrectValueForParam() { - String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; - String CONTACT_PHONE_NUMBER = "contact_phone_number"; + String MOTHER_GUARDIAN_PHONE_NUMBER = "mother_contact_phone_number"; + String CONTACT_PHONE_NUMBER = "contact_phone_number"; - MockHttpServletRequest req = new MockHttpServletRequest(); - req.addParameter(MOTHER_GUARDIAN_PHONE_NUMBER, "+254738388383"); - req.addParameter(CONTACT_PHONE_NUMBER, "+2547112233445"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.addParameter(MOTHER_GUARDIAN_PHONE_NUMBER, "+254738388383"); + req.addParameter(CONTACT_PHONE_NUMBER, "+2547112233445"); - String motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); + String motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); - Assert.assertNotNull(motherGuardianNum); - Assert.assertEquals("+254738388383", motherGuardianNum); + Assert.assertNotNull(motherGuardianNum); + Assert.assertEquals("+254738388383", motherGuardianNum); - req.removeParameter(MOTHER_GUARDIAN_PHONE_NUMBER); - motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); + req.removeParameter(MOTHER_GUARDIAN_PHONE_NUMBER); + motherGuardianNum = SearchHelper.getContactPhoneNumberParam(req); - Assert.assertNotNull(motherGuardianNum); - Assert.assertEquals("+2547112233445", motherGuardianNum); - } + Assert.assertNotNull(motherGuardianNum); + Assert.assertEquals("+2547112233445", motherGuardianNum); + } - @Test - public void testIntersectionReturnsEmptyListIfBothListsEmptyOrNull() { + @Test + public void testIntersectionReturnsEmptyListIfBothListsEmptyOrNull() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - List list2 = new ArrayList<>(); + List list2 = new ArrayList<>(); - List resultList = SearchHelper.intersection(list, list2); + List resultList = SearchHelper.intersection(list, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(0, resultList.size()); + Assert.assertNotNull(resultList); + Assert.assertEquals(0, resultList.size()); - resultList = SearchHelper.intersection(new ArrayList(), new ArrayList()); + resultList = SearchHelper.intersection(new ArrayList(), new ArrayList()); - Assert.assertNotNull(resultList); - Assert.assertEquals(0, resultList.size()); + Assert.assertNotNull(resultList); + Assert.assertEquals(0, resultList.size()); - } + } - @Test - public void testIntersectionReturnsClientListAIfClientBListIsNullOrEmpty() { + @Test + public void testIntersectionReturnsClientListAIfClientBListIsNullOrEmpty() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client = new Client("dummy-base-entity-id_1"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + Client client = new Client("dummy-base-entity-id_1"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - Client client2 = new Client("dummy-base-entity-id_2"); - client2.setFirstName("Jane"); - client2.setLastName("Test"); - client2.setGender("FEMALE"); + Client client2 = new Client("dummy-base-entity-id_2"); + client2.setFirstName("Jane"); + client2.setLastName("Test"); + client2.setGender("FEMALE"); - list.add(client); - list.add(client2); + list.add(client); + list.add(client2); - List resultList = SearchHelper.intersection(list, null); + List resultList = SearchHelper.intersection(list, null); - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - resultList = SearchHelper.intersection(list, new ArrayList()); + resultList = SearchHelper.intersection(list, new ArrayList()); - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - } + } - @Test - public void testIntersectionReturnsClientListBIfClientAListIsNullOrEmpty() { + @Test + public void testIntersectionReturnsClientListBIfClientAListIsNullOrEmpty() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client3 = new Client("dummy-base-entity-id_3"); - client3.setFirstName("James"); - client3.setLastName("Dean"); - client3.setGender("MALE"); + Client client3 = new Client("dummy-base-entity-id_3"); + client3.setFirstName("James"); + client3.setLastName("Dean"); + client3.setGender("MALE"); - Client client4 = new Client("dummy-base-entity-id_1"); - client4.setFirstName("Johnny"); - client4.setLastName("Test"); - client4.setGender("MALE"); + Client client4 = new Client("dummy-base-entity-id_1"); + client4.setFirstName("Johnny"); + client4.setLastName("Test"); + client4.setGender("MALE"); - Client client5 = new Client("dummy-base-entity-id_2"); - client5.setFirstName("Jane"); - client5.setLastName("Test"); - client5.setGender("FEMALE"); + Client client5 = new Client("dummy-base-entity-id_2"); + client5.setFirstName("Jane"); + client5.setLastName("Test"); + client5.setGender("FEMALE"); - List list2 = new ArrayList<>(); + List list2 = new ArrayList<>(); - list2.add(client3); - list2.add(client4); - list2.add(client5); + list2.add(client3); + list2.add(client4); + list2.add(client5); - List resultList = SearchHelper.intersection(list, list2); + List resultList = SearchHelper.intersection(list, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(3, resultList.size()); - Assert.assertEquals("James", resultList.get(0).getFirstName()); - Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); - Assert.assertEquals("Jane", resultList.get(2).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(3, resultList.size()); + Assert.assertEquals("James", resultList.get(0).getFirstName()); + Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); + Assert.assertEquals("Jane", resultList.get(2).getFirstName()); - resultList = SearchHelper.intersection(null, list2); + resultList = SearchHelper.intersection(null, list2); - Assert.assertNotNull(resultList); - Assert.assertEquals(3, resultList.size()); - Assert.assertEquals("James", resultList.get(0).getFirstName()); - Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); - Assert.assertEquals("Jane", resultList.get(2).getFirstName()); + Assert.assertNotNull(resultList); + Assert.assertEquals(3, resultList.size()); + Assert.assertEquals("James", resultList.get(0).getFirstName()); + Assert.assertEquals("Johnny", resultList.get(1).getFirstName()); + Assert.assertEquals("Jane", resultList.get(2).getFirstName()); - } + } - @Test - public void testIntersectionReturnsAConjunctionOfTwoClientLists() { + @Test + public void testIntersectionReturnsAConjunctionOfTwoClientLists() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - Client client = new Client("dummy-base-entity-id_1"); - client.setFirstName("Johnny"); - client.setLastName("Test"); - client.setGender("MALE"); + Client client = new Client("dummy-base-entity-id_1"); + client.setFirstName("Johnny"); + client.setLastName("Test"); + client.setGender("MALE"); - Client client2 = new Client("dummy-base-entity-id_2"); - client2.setFirstName("Jane"); - client2.setLastName("Test"); - client2.setGender("FEMALE"); - - list.add(client); - list.add(client2); - - Client client3 = new Client("dummy-base-entity-id_3"); - client3.setFirstName("James"); - client3.setLastName("Dean"); - client3.setGender("MALE"); - - Client client4 = new Client("dummy-base-entity-id_1"); - client4.setFirstName("Johnny"); - client4.setLastName("Test"); - client4.setGender("MALE"); - - Client client5 = new Client("dummy-base-entity-id_2"); - client5.setFirstName("Jane"); - client5.setLastName("Test"); - client5.setGender("FEMALE"); - - List list2 = new ArrayList<>(); - - list2.add(client3); - list2.add(client4); - list2.add(client5); - - List resultList = SearchHelper.intersection(list, list2); - - Assert.assertNotNull(resultList); - Assert.assertEquals(2, resultList.size()); - Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); - Assert.assertEquals("Jane", resultList.get(1).getFirstName()); - - } - - @Test - public void childSearchParamProcessorShouldHaveCorrectIdentifierWhenCreatingBean() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("20"); - Mockito.when(httpServletRequest.getParameter("opensrp_id")).thenReturn("2093980"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); - String result = searchEntityWrapper.getClientSearchBean().getIdentifiers().get("opensrp_id"); - Assert.assertEquals("2093980", result); - } - - @Test - public void testProcessSearchResult() { - final String mother = "mother"; - - Client motherClient = new Client("dummy-mother-base-entity-id"); - motherClient.setFirstName("Jane"); - motherClient.setLastName("Doe"); - motherClient.setGender("FEMALE"); - motherClient.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); - List motherList = new ArrayList<>(); - motherList.add(motherClient); - - List list = new ArrayList<>(); - list.add("dummy-mother-base-entity-id"); - - Map> relationships = new HashMap<>(); - relationships.put(mother, list); - - Client child = new Client("dummy-mother-base-entity-id"); - child.setFirstName("John"); - child.setLastName("Doe"); - child.setGender("Male"); - child.setRelationships(relationships); - child.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); - - List childList = new ArrayList<>(); - childList.add(child); - - List childMothers = SearchHelper.processSearchResult(childList, motherList, mother); - Assert.assertEquals(1, childMothers.size()); - Assert.assertEquals("John Doe", childMothers.get(0).getChild().fullName()); - } - - @Test - public void testMotherSearchParamProcessorForHttpServletRequest() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("0"); - Mockito.when(httpServletRequest.getParameter("mother_first_name")).thenReturn("Jane"); - Mockito.when(httpServletRequest.getParameter("mother_last_name")).thenReturn("Doe"); - Mockito.when(httpServletRequest.getParameter("mother_nrc_number")).thenReturn("2093980"); - Mockito.when(httpServletRequest.getParameter("NRC_Number")).thenReturn("20939801123"); - Mockito.when(httpServletRequest.getParameter("mother_compass_relationship_id")).thenReturn("dab102f71bd"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(httpServletRequest); - Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(2, result.size()); - Assert.assertTrue(result.containsKey("NRC_Number")); - Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); - Assert.assertEquals("2093980", result.get("NRC_Number")); - } - - @Test - public void testMotherSearchParamProcessorForJSONObject() throws ParseException { - JSONObject jsonObject = Mockito.mock(JSONObject.class); - Mockito.when(jsonObject.optString("limit")).thenReturn("0"); - Mockito.when(jsonObject.optString("mother_first_name")).thenReturn("Jane"); - Mockito.when(jsonObject.optString("mother_last_name")).thenReturn("Doe"); - Mockito.when(jsonObject.optString("mother_nrc_number")).thenReturn("2093980"); - Mockito.when(jsonObject.optString("NRC_Number")).thenReturn("20939801123"); - Mockito.when(jsonObject.optString("mother_compass_relationship_id")).thenReturn("dab102f71bd"); - Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); - SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(jsonObject); - Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(2, result.size()); - Assert.assertTrue(result.containsKey("NRC_Number")); - Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); - Assert.assertEquals("2093980", result.get("NRC_Number")); - } - - @Test - public void testChildSearchParamProcessorForJSONObject() throws ParseException { - JSONObject jsonObject = Mockito.mock(JSONObject.class); - Mockito.when(jsonObject.optString("limit")).thenReturn("50"); - Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); - Mockito.when(jsonObject.optString(SearchHelper.BIRTH_DATE)).thenReturn(""); - Mockito.when(jsonObject.optString(SearchHelper.ZEIR_ID)).thenReturn("1234"); - Mockito.when(jsonObject.optString(SearchHelper.OPENSRP_ID)).thenReturn("4567"); - Mockito.when(jsonObject.optString(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); - Mockito.when(jsonObject.optString(SearchHelper.INACTIVE)).thenReturn("false"); - Mockito.when(jsonObject.optString(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); - Mockito.when(jsonObject.optString(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(jsonObject); - - Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(3, attributes.size()); - - Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); - Assert.assertEquals(4, identifiers.size()); - - Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); - Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key - Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); - - Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); - Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); - Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); - - Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); - Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); - } - - @Test - public void testChildSearchParamProcessorForHttpServletRequest() throws ParseException { - HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("50"); - Mockito.when(httpServletRequest.getParameter("lastEdited")).thenReturn(""); - Mockito.when(httpServletRequest.getParameter(SearchHelper.BIRTH_DATE)).thenReturn(""); - Mockito.when(httpServletRequest.getParameter(SearchHelper.ZEIR_ID)).thenReturn("1234"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.OPENSRP_ID)).thenReturn("4567"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.INACTIVE)).thenReturn("false"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); - Mockito.when(httpServletRequest.getParameter(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); - SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); - - Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); - Assert.assertEquals(3, attributes.size()); - - Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); - Assert.assertEquals(4, identifiers.size()); - - Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); - Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key - Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); - - Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); - Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); - Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); - - Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); - Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); - } - - @Test - public void testSetCoreFiltersForJSONObjectWithIntegerLimitReturnsValue() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("limit", 50); - try { - int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); - Assert.assertEquals(50, result); - } catch (ParseException e) { - e.printStackTrace(); - } - } - - @Test - public void testSetCoreFiltersForJSONObjectWithStringLimitReturnsValue() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("limit", "50"); - try { - int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); - Assert.assertEquals(50, result); - } catch (ParseException e) { - e.printStackTrace(); - } - } + Client client2 = new Client("dummy-base-entity-id_2"); + client2.setFirstName("Jane"); + client2.setLastName("Test"); + client2.setGender("FEMALE"); + + list.add(client); + list.add(client2); + + Client client3 = new Client("dummy-base-entity-id_3"); + client3.setFirstName("James"); + client3.setLastName("Dean"); + client3.setGender("MALE"); + + Client client4 = new Client("dummy-base-entity-id_1"); + client4.setFirstName("Johnny"); + client4.setLastName("Test"); + client4.setGender("MALE"); + + Client client5 = new Client("dummy-base-entity-id_2"); + client5.setFirstName("Jane"); + client5.setLastName("Test"); + client5.setGender("FEMALE"); + + List list2 = new ArrayList<>(); + + list2.add(client3); + list2.add(client4); + list2.add(client5); + + List resultList = SearchHelper.intersection(list, list2); + + Assert.assertNotNull(resultList); + Assert.assertEquals(2, resultList.size()); + Assert.assertEquals("Johnny", resultList.get(0).getFirstName()); + Assert.assertEquals("Jane", resultList.get(1).getFirstName()); + + } + + @Test + public void childSearchParamProcessorShouldHaveCorrectIdentifierWhenCreatingBean() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("20"); + Mockito.when(httpServletRequest.getParameter("opensrp_id")).thenReturn("2093980"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); + String result = searchEntityWrapper.getClientSearchBean().getIdentifiers().get("opensrp_id"); + Assert.assertEquals("2093980", result); + } + + @Test + public void testProcessSearchResult() { + final String mother = "mother"; + + Client motherClient = new Client("dummy-mother-base-entity-id"); + motherClient.setFirstName("Jane"); + motherClient.setLastName("Doe"); + motherClient.setGender("FEMALE"); + motherClient.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); + List motherList = new ArrayList<>(); + motherList.add(motherClient); + + List list = new ArrayList<>(); + list.add("dummy-mother-base-entity-id"); + + Map> relationships = new HashMap<>(); + relationships.put(mother, list); + + Client child = new Client("dummy-mother-base-entity-id"); + child.setFirstName("John"); + child.setLastName("Doe"); + child.setGender("Male"); + child.setRelationships(relationships); + child.setIdentifiers(EasyMap.mapOf("M_ZEIR_ID", "673939_mother")); + + List childList = new ArrayList<>(); + childList.add(child); + + List childMothers = SearchHelper.processSearchResult(childList, motherList, mother); + Assert.assertEquals(1, childMothers.size()); + Assert.assertEquals("John Doe", childMothers.get(0).getChild().fullName()); + } + + @Test + public void testMotherSearchParamProcessorForHttpServletRequest() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("0"); + Mockito.when(httpServletRequest.getParameter("mother_first_name")).thenReturn("Jane"); + Mockito.when(httpServletRequest.getParameter("mother_last_name")).thenReturn("Doe"); + Mockito.when(httpServletRequest.getParameter("mother_nrc_number")).thenReturn("2093980"); + Mockito.when(httpServletRequest.getParameter("NRC_Number")).thenReturn("20939801123"); + Mockito.when(httpServletRequest.getParameter("mother_compass_relationship_id")).thenReturn("dab102f71bd"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(httpServletRequest); + Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(2, result.size()); + Assert.assertTrue(result.containsKey("NRC_Number")); + Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); + Assert.assertEquals("2093980", result.get("NRC_Number")); + } + + @Test + public void testMotherSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("0"); + Mockito.when(jsonObject.optString("mother_first_name")).thenReturn("Jane"); + Mockito.when(jsonObject.optString("mother_last_name")).thenReturn("Doe"); + Mockito.when(jsonObject.optString("mother_nrc_number")).thenReturn("2093980"); + Mockito.when(jsonObject.optString("NRC_Number")).thenReturn("20939801123"); + Mockito.when(jsonObject.optString("mother_compass_relationship_id")).thenReturn("dab102f71bd"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + SearchEntityWrapper searchEntityWrapper = SearchHelper.motherSearchParamProcessor(jsonObject); + Map result = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(2, result.size()); + Assert.assertTrue(result.containsKey("NRC_Number")); + Assert.assertTrue(result.containsKey("Compass_Relationship_ID")); + Assert.assertEquals("2093980", result.get("NRC_Number")); + } + + @Test + public void testChildSearchParamProcessorForJSONObject() throws ParseException { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.optString("limit")).thenReturn("50"); + Mockito.when(jsonObject.optString("lastEdited")).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(jsonObject.optString(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(jsonObject.optString(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(jsonObject.optString(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(jsonObject.optString(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(jsonObject.optString(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(jsonObject.optString(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(jsonObject); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testChildSearchParamProcessorForHttpServletRequest() throws ParseException { + HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getParameter("limit")).thenReturn("50"); + Mockito.when(httpServletRequest.getParameter("lastEdited")).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.BIRTH_DATE)).thenReturn(""); + Mockito.when(httpServletRequest.getParameter(SearchHelper.ZEIR_ID)).thenReturn("1234"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.OPENSRP_ID)).thenReturn("4567"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.SIM_PRINT_GUID)).thenReturn("91011"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.INACTIVE)).thenReturn("false"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.LOST_TO_FOLLOW_UP)).thenReturn("true"); + Mockito.when(httpServletRequest.getParameter(SearchHelper.NFC_CARD_IDENTIFIER)).thenReturn("nfc_card_identifier_1"); + SearchEntityWrapper searchEntityWrapper = SearchHelper.childSearchParamProcessor(httpServletRequest); + + Map attributes = searchEntityWrapper.getClientSearchBean().getAttributes(); + Assert.assertEquals(3, attributes.size()); + + Map identifiers = searchEntityWrapper.getClientSearchBean().getIdentifiers(); + Assert.assertEquals(4, identifiers.size()); + + Assert.assertTrue(identifiers.containsKey(SearchHelper.ZEIR_ID)); + Assert.assertTrue(identifiers.containsKey("ZEIR_ID")); //check backward compatibility with upper case key + Assert.assertTrue(identifiers.containsKey(SearchHelper.SIM_PRINT_GUID)); + + Assert.assertTrue(attributes.containsKey(SearchHelper.INACTIVE)); + Assert.assertTrue(attributes.containsKey(SearchHelper.LOST_TO_FOLLOW_UP)); + Assert.assertTrue(attributes.containsKey("NFC_Card_Identifier")); + + Assert.assertEquals(identifiers.get(SearchHelper.ZEIR_ID), "1234"); + Assert.assertEquals(attributes.get("NFC_Card_Identifier"), "nfc_card_identifier_1"); + } + + @Test + public void testSetCoreFiltersForJSONObjectWithIntegerLimitReturnsValue() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", 50); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50, result); + } + catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testSetCoreFiltersForJSONObjectWithStringLimitReturnsValue() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("limit", "50"); + try { + int result = SearchHelper.setCoreFilters(jsonObject, new ClientSearchBean()); + Assert.assertEquals(50, result); + } + catch (ParseException e) { + e.printStackTrace(); + } + } } diff --git a/src/test/java/org/opensrp/web/utils/UtilsTest.java b/src/test/java/org/opensrp/web/utils/UtilsTest.java index 4d62726a1..f45c981db 100644 --- a/src/test/java/org/opensrp/web/utils/UtilsTest.java +++ b/src/test/java/org/opensrp/web/utils/UtilsTest.java @@ -13,38 +13,38 @@ import org.opensrp.web.config.Role; public class UtilsTest { - + @Test public void testGetStringFromJSONForObject() { - + JSONObject obj = new JSONObject(); obj.put("location", "Roysa"); - + String result = Utils.getStringFromJSON(obj, "location"); - + Assert.assertNotNull(result); Assert.assertEquals("Roysa", result); } - + @Test public void testGetStringFromJSONForArray() { - + JSONArray obj = new JSONArray(); obj.put("address1"); obj.put("address2"); obj.put("address3"); - + JSONObject parentObj = new JSONObject(); parentObj.put("addresses", obj); - + String result = Utils.getStringFromJSON(parentObj, "addresses"); - + Assert.assertNotNull(result); Assert.assertEquals("[\"address1\",\"address2\",\"address3\"]", result); } @Test - public void testGetDateTimeFromStringShouldReturnDate(){ + public void testGetDateTimeFromStringShouldReturnDate() { Date date = Utils.getDateFromString("1615895228000"); Assert.assertNotNull(date); Calendar calendar = Calendar.getInstance(); @@ -55,7 +55,7 @@ public void testGetDateTimeFromStringShouldReturnDate(){ } @Test - public void testGetDateTimeFromStringShouldReturnNull(){ + public void testGetDateTimeFromStringShouldReturnNull() { Date date = Utils.getDateFromString("wrongdate"); Assert.assertNull(date); date = Utils.getDateFromString(null); @@ -64,20 +64,20 @@ public void testGetDateTimeFromStringShouldReturnNull(){ @Test public void testCheckRoleIfRoleExists() { - + List roleList = new ArrayList<>(); roleList.add(Role.OPENSRP_GENERATE_QR_CODE); roleList.add(Role.PII_DATA_MASK); roleList.add(Role.PLANS_FOR_USER); - + boolean result = Utils.checkRoleIfRoleExists(roleList, Role.PLANS_FOR_USER); Assert.assertTrue(result); - + result = Utils.checkRoleIfRoleExists(roleList, Role.OPENSRP_GENERATE_QR_CODE.toUpperCase(Locale.ENGLISH)); Assert.assertTrue(result); - + result = Utils.checkRoleIfRoleExists(roleList, Role.OPENMRS); Assert.assertFalse(result); - + } } From ae921d4d3c4b19abe727a88736f911c22ba675b0 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Tue, 17 Jan 2023 13:36:43 +0300 Subject: [PATCH 20/27] initialize variable --- src/main/java/org/opensrp/web/rest/RestUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 50d1c567a..ad3fbbd23 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -76,7 +76,7 @@ public static DateTime getDateFilter(String filter, HttpServletRequest req) thro } public static DateTime[] getDateRangeFilter(String filter, Object object) throws ParseException { - String strval; + String strval = null; if (object instanceof HttpServletRequest) { HttpServletRequest req = (HttpServletRequest) object; From e2004db067810af8e541c06bbc335d3a7c43edc7 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 20 Jan 2023 11:54:12 +0300 Subject: [PATCH 21/27] fix codacy issue --- src/main/java/org/opensrp/web/rest/SearchResource.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 78a3be5e0..1f7aeb916 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -76,7 +76,7 @@ public SearchResource(SearchService searchService, ClientService clientService, @Override public List search(HttpServletRequest request) throws ParseException {//TODO search should not call different url but only add params - Pair> result = extractNamesAndCreateClientSearchBean(request); + Pair> result = extractSearchParams(request); return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); } @@ -84,7 +84,7 @@ public List search(HttpServletRequest request) @RequestMapping(method = RequestMethod.POST, value = "/search", produces = { MediaType.APPLICATION_JSON_VALUE }) public List searchByPost(@RequestBody String jsonRequestBody) throws ParseException {//TODO search should not call different url but only add params - Pair> result = extractNamesAndCreateClientSearchBean( + Pair> result = extractSearchParams( jsonRequestBody); return searchService.searchClient(result.getLeft(), result.getRight().getLeft(), result.getRight().getMiddle(), result.getRight().getRight(), null); @@ -209,7 +209,7 @@ public List getClientBaseEntityIdsByContactPhoneNumber(String motherGuar return clientBaseEntityIds; } - public Pair> extractNamesAndCreateClientSearchBean(Object object) + public Pair> extractSearchParams(Object object) throws ParseException { String firstName; From 1fdcb9f5c4dd4a719407aa7fce6ec55c4fe54116 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Fri, 20 Jan 2023 14:35:11 +0300 Subject: [PATCH 22/27] revert to clientService methods without acl --- src/main/java/org/opensrp/web/rest/SearchResource.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/SearchResource.java b/src/main/java/org/opensrp/web/rest/SearchResource.java index 1f7aeb916..449939a10 100644 --- a/src/main/java/org/opensrp/web/rest/SearchResource.java +++ b/src/main/java/org/opensrp/web/rest/SearchResource.java @@ -143,7 +143,7 @@ private List searchAndProcess(SearchEntityWrapper childSearchEntity List clientBaseEntityIds = getClientBaseEntityIdsByContactPhoneNumber(contactPhoneNumber); - List eventChildren = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); + List eventChildren = clientService.findGlobalByFieldValue(BaseEntity.BASE_ENTITY_ID, clientBaseEntityIds); children = SearchHelper.intersection(children, eventChildren);// Search conjunction is "AND" find intersection @@ -159,7 +159,7 @@ private List searchAndProcess(SearchEntityWrapper childSearchEntity } } - linkedMothers = clientService.findByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); + linkedMothers = clientService.findGlobalByFieldValue(BaseEntity.BASE_ENTITY_ID, clientIds); } @@ -167,7 +167,7 @@ private List searchAndProcess(SearchEntityWrapper childSearchEntity if (!mothers.isEmpty()) { for (Client client : mothers) { - linkedChildren.addAll(clientService.findByRelationship(client.getBaseEntityId())); + linkedChildren.addAll(clientService.findGlobalByRelationship(client.getBaseEntityId())); } } From 19aaee846e49375677e1d1e32bae7592be91fa33 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 23 Jan 2023 10:37:55 +0300 Subject: [PATCH 23/27] create alpha snapshot for testing --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bced9f9c1..61177c484 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 6.1.6.RELEASE always 1.5.1 - 3.2.8-SNAPSHOT + 3.2.8-ALPHA-SNAPSHOT 2.4.1-SNAPSHOT 2.0.1-SNAPSHOT 2.0.5 From 8d879be6d254965b06ca3e929b2f929d3e6bd35c Mon Sep 17 00:00:00 2001 From: hilpitome Date: Mon, 23 Jan 2023 10:50:51 +0300 Subject: [PATCH 24/27] version as alpha --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 61177c484..475b410b6 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ opensrp-server-web war - 3.2.11-SNAPSHOT + 3.2.11-ALPHA-SNAPSHOT opensrp-server-web OpenSRP Server Web Application https://github.com/OpenSRP/opensrp-server-web @@ -25,7 +25,7 @@ 6.1.6.RELEASE always 1.5.1 - 3.2.8-ALPHA-SNAPSHOT + 3.2.8-SNAPSHOT 2.4.1-SNAPSHOT 2.0.1-SNAPSHOT 2.0.5 From d7c6e72f7893e61903c2d6051be1c36c3688bbfe Mon Sep 17 00:00:00 2001 From: Hilary Baraka Egesa Date: Tue, 7 Mar 2023 09:46:36 +0300 Subject: [PATCH 25/27] bump up version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 475b410b6..7bf491c98 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ opensrp-server-web war - 3.2.11-ALPHA-SNAPSHOT + 3.2.12-SNAPSHOT opensrp-server-web OpenSRP Server Web Application https://github.com/OpenSRP/opensrp-server-web From 17942f6d9a8ecb82b33f8be63191b0dc04bc8143 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Wed, 8 Mar 2023 20:42:11 +0300 Subject: [PATCH 26/27] add logging --- src/main/java/org/opensrp/web/rest/RestUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index ad3fbbd23..510395a63 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -103,9 +103,9 @@ public static boolean getBooleanFilter(String filter, HttpServletRequest req) { return Boolean.parseBoolean(stringFilter); } - public static void main(String[] args) { - System.out.println(new DateTime("​1458932400000")); - } + //public static void main(String[] args) { + // System.out.println(new DateTime("​1458932400000")); + //} public static synchronized String setDateFilter(Date date) throws ParseException { return date == null ? null : SDF.format(date); @@ -124,11 +124,11 @@ public static void verifyRequiredProperties(List properties, T entit } } catch (IllegalArgumentException e) { - e.printStackTrace(); + logger.error(e); throw new RuntimeException("A required field " + p + " was not found in resource class"); } catch (IllegalAccessException e) { - e.printStackTrace(); + logger.error(e); } } } From b229f88929b6e71a15dbc1274d34eff70e51d674 Mon Sep 17 00:00:00 2001 From: hilpitome Date: Thu, 9 Mar 2023 11:27:43 +0300 Subject: [PATCH 27/27] refactor getStringFilter mthd --- src/main/java/org/opensrp/web/rest/RestUtils.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/opensrp/web/rest/RestUtils.java b/src/main/java/org/opensrp/web/rest/RestUtils.java index 510395a63..d392ce830 100644 --- a/src/main/java/org/opensrp/web/rest/RestUtils.java +++ b/src/main/java/org/opensrp/web/rest/RestUtils.java @@ -48,7 +48,7 @@ public static String getStringFilter(String filter, HttpServletRequest req) { } public static String getStringFilter(String filter, JSONObject jsonObject) { - return StringUtils.isBlank(jsonObject.optString(filter)) ? null : jsonObject.optString(filter); + return jsonObject.optString(filter); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -103,10 +103,6 @@ public static boolean getBooleanFilter(String filter, HttpServletRequest req) { return Boolean.parseBoolean(stringFilter); } - //public static void main(String[] args) { - // System.out.println(new DateTime("​1458932400000")); - //} - public static synchronized String setDateFilter(Date date) throws ParseException { return date == null ? null : SDF.format(date); }