diff --git a/assets/config/opensrp.properties b/assets/config/opensrp.properties index 60e5b9a0e0..74d09bf1fd 100644 --- a/assets/config/opensrp.properties +++ b/assets/config/opensrp.properties @@ -1,3 +1,12 @@ +sms.can.be.sent=false +number.of.audit.messages=1000 +mcts.phone.number=8762963816 +mcts-report-delay-in-days=10 +mcts.poll.time.interval.in.minutes=10 + +multimedia.directory.name==/multimedia +multimedia.datastore.directory=D:/testopensrp + form.poll.time.interval=2 js.directory.name=/ziggy form.directory.name=/form @@ -6,6 +15,8 @@ form.download.files=form.xml, model.xml, form_definition.json # scheduler properties schedule.config.path=/schedules/schedule-config.xls preferred.time=7 + +admin.task.token=2928392302302930293029302 openmrs.scheduletracker.syncer.interval-min=2 # OpenMRS configuration @@ -24,7 +35,7 @@ couchdb.opensrp-db.revision-limit=1 jdbc.backend=mysql jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.username=root -jdbc.password=passw +jdbc.password=password #jdbc url with server and port but without database jdbc.url-wo-db=jdbc:mysql://localhost:3306 diff --git a/assets/config/quartz.properties b/assets/config/quartz.properties index eece4a9839..dbcd45408b 100644 --- a/assets/config/quartz.properties +++ b/assets/config/quartz.properties @@ -1,17 +1,17 @@ -org.quartz.scheduler.instanceName = MotechScheduler -org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool -org.quartz.threadPool.threadCount = 3 +org.quartz.scheduler.instanceName=MotechScheduler +org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool +org.quartz.threadPool.threadCount=3 -org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX -org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate -org.quartz.jobStore.dataSource = motechDS -org.quartz.jobStore.tablePrefix = QRTZ_ +org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX +org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +org.quartz.jobStore.dataSource=motechDS +org.quartz.jobStore.tablePrefix=QRTZ_ -org.quartz.dataSource.motechDS.db = etbmotechquartz -org.quartz.dataSource.motechDS.driver = com.mysql.jdbc.Driver -org.quartz.dataSource.motechDS.URL = jdbc:mysql://localhost:3306/etbmotechquartz -org.quartz.dataSource.motechDS.user = root -org.quartz.dataSource.motechDS.password = password -org.quartz.dataSource.motechDS.maxConnections = 30 +org.quartz.dataSource.motechDS.db=motechquartz +org.quartz.dataSource.motechDS.driver=com.mysql.jdbc.Driver +org.quartz.dataSource.motechDS.URL=jdbc:mysql://localhost:3306/motechquartz +org.quartz.dataSource.motechDS.user=root +org.quartz.dataSource.motechDS.password=password +org.quartz.dataSource.motechDS.maxConnections=30 -#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore +#org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore diff --git a/build/maven.properties b/build/maven.properties index 4518376f58..c4bb6c8918 100644 --- a/build/maven.properties +++ b/build/maven.properties @@ -1,9 +1,17 @@ #database configuration that is compiled on maven build time and is not likely to change unless massive refactoring -couchdb.db.opensrp=etb-opensrp -couchdb.db.form=etb-opensrp-form -couchdb.db.atomfeed=etb-atomfeed -couchdb.db.mcts=etb-opensrp-mcts -couchdb.db.error=etb-opensrp-errortrace +couchdb.db.opensrp=opensrp +couchdb.db.client=opensrp-client +couchdb.db.event=opensrp-event +couchdb.db.alert=opensrp-alert +couchdb.db.action=opensrp-action +couchdb.db.drugorder=opensrp-drugorder +couchdb.db.location=opensrp-location +couchdb.db.multimedia=opensrp-multimedia +couchdb.db.provider=opensrp-provider +couchdb.db.form=opensrp-form +couchdb.db.atomfeed=atomfeed +couchdb.db.mcts=opensrp-mcts +couchdb.db.error=opensrp-errortrace db.reporting=opensrp db.reporting.report=report diff --git a/opensrp-api/src/main/java/org/opensrp/api/domain/Drug.java b/opensrp-api/src/main/java/org/opensrp/api/domain/Drug.java new file mode 100644 index 0000000000..9a03e8ba61 --- /dev/null +++ b/opensrp-api/src/main/java/org/opensrp/api/domain/Drug.java @@ -0,0 +1,146 @@ +package org.opensrp.api.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonProperty; +import org.ektorp.support.TypeDiscriminator; +import org.joda.time.LocalDate; +import org.motechproject.model.MotechBaseDataObject; + +@TypeDiscriminator("doc.type === 'Drug'") +public class Drug extends BaseDataObject { + @JsonProperty + private String drugName; + @JsonProperty + private String drugBaseName; + @JsonProperty + private Map codes; + @JsonProperty + private String route; + @JsonProperty + private String id; + @JsonProperty + private String creator; + @JsonProperty + private String doseStrength; + @JsonProperty + private String units; + @JsonProperty + private String maximumDailyDose; + @JsonProperty + private String minimumDailyDose; + @JsonProperty + private String description; + + + @JsonProperty + private String combination; + + + protected Drug() { + + } + + public Drug(String baseEntityId) { + + } + public Drug(String drugName,String drugBaseName, Map codes, + String route, String creator, String doseStrenght + , String units, String maxDailyDose,String miniDailyDose,String Description,String combination) { + this.drugName=drugName; + this.drugBaseName=drugBaseName; + this.codes=codes; + this.creator=creator; + this.doseStrength=doseStrenght; + this.route=route; + this.maximumDailyDose=maxDailyDose; + this.minimumDailyDose=miniDailyDose; + this.description=Description; + this.combination=combination; + + + } + @Override + public boolean equals(Object o) { + return EqualsBuilder.reflectionEquals(this, o); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this, "id"); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + public String getDoseStrength() { + return doseStrength; + } + + public void setDoseStrength(String doseStrength) { + this.doseStrength = doseStrength; + } + + public String getUnits() { + return units; + } + + public void setUnits(String units) { + this.units = units; + } + + public String getMaximumDailyDose() { + return maximumDailyDose; + } + + public void setMaximumDailyDose(String maximumDailyDose) { + this.maximumDailyDose = maximumDailyDose; + } + + public String getMinimumDailyDose() { + return minimumDailyDose; + } + + public void setMinimumDailyDose(String minimumDailyDose) { + this.minimumDailyDose = minimumDailyDose; + } + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + public String getDescription() { + return description; + } + + + public String getCreatorName() { + return creator; + } + + public void setCreatorName(String creator) { + this.creator = creator; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCombination() { + return combination; + } + + public void setCombination(String combination) { + this.combination = combination; + } +} diff --git a/opensrp-api/src/main/java/org/opensrp/api/domain/DrugOrder.java b/opensrp-api/src/main/java/org/opensrp/api/domain/DrugOrder.java new file mode 100644 index 0000000000..724c7818b6 --- /dev/null +++ b/opensrp-api/src/main/java/org/opensrp/api/domain/DrugOrder.java @@ -0,0 +1,204 @@ +package org.opensrp.api.domain; + +import java.util.Map; + +import org.codehaus.jackson.annotate.JsonProperty; +import org.ektorp.support.TypeDiscriminator; + +@TypeDiscriminator("doc.type == 'DrugOrder'") +public class DrugOrder extends BaseDataObject { + + @JsonProperty + private Map codes; + @JsonProperty + private String orderType; + @JsonProperty + private String drugName; + @JsonProperty + private String orderNumber; + @JsonProperty + private String action; + @JsonProperty + private String previousOrder; + @JsonProperty + private String dateActivated; + @JsonProperty + private String dateStopped; + @JsonProperty + private String autoExpireDate; + @JsonProperty + private String urgency; + @JsonProperty + private String instructions; + @JsonProperty + private String orderReason; + @JsonProperty + private String dosingType; + @JsonProperty + private String dose; + @JsonProperty + private String descriptions; + @JsonProperty + private String quantity; + + public DrugOrder(String drugName,String orderType, Map codes, + String orderNumber, String action, String previousOrder + , String dateActivated, String dateStopped,String autoExpireDate,String urgency, + String instructions, String dosingType, String description,String quantity) + { + this.drugName=drugName; + this.orderType=orderType; + this.codes=codes; + this.orderNumber=orderNumber; + this.action=action; + this.previousOrder=previousOrder; + this.dateActivated=dateActivated; + this.dateStopped=dateStopped; + this.autoExpireDate=autoExpireDate; + this.urgency=urgency; + this.instructions=instructions; + this.dosingType=dosingType; + this.descriptions=description; + this.quantity=quantity; + } + + public DrugOrder() + { + + } + + public DrugOrder(String drugName) + { + this.drugName=drugName; + } + public Map getCodes() { + return codes; + } + + public void setCodes(Map codes) { + this.codes = codes; + } + + + + public String getOrderType() { + return orderType; + } + + public void setOrderType(String orderType) { + this.orderType = orderType; + } + + public String getDrugName() { + return drugName; + } + + public void setDrugName(String drugName) { + this.drugName = drugName; + } + + public String getOrderNumber() { + return orderNumber; + } + + public void setOrderNumber(String orderNumber) { + this.orderNumber = orderNumber; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getPreviousOrder() { + return previousOrder; + } + + public void setPreviousOrder(String previousOrder) { + this.previousOrder = previousOrder; + } + + public String getDateActivated() { + return dateActivated; + } + + public void setDateActivated(String dateActivated) { + this.dateActivated = dateActivated; + } + + public String getDateStopped() { + return dateStopped; + } + + public void setDateStopped(String dateStopped) { + this.dateStopped = dateStopped; + } + + public String getAutoExpireDate() { + return autoExpireDate; + } + + public void setAutoExpireDate(String autoExpireDate) { + this.autoExpireDate = autoExpireDate; + } + + public String getUrgency() { + return urgency; + } + + public void setUrgency(String urgency) { + this.urgency = urgency; + } + + public String getInstructions() { + return instructions; + } + + public void setInstructions(String instructions) { + this.instructions = instructions; + } + + public String getOrderReason() { + return orderReason; + } + + public void setOrderReason(String orderReason) { + this.orderReason = orderReason; + } + + public String getDosingType() { + return dosingType; + } + + public void setDosingType(String dosingType) { + this.dosingType = dosingType; + } + + public String getDose() { + return dose; + } + + public void setDose(String dose) { + this.dose = dose; + } + + public String getDescriptions() { + return descriptions; + } + + public void setDescriptions(String descriptions) { + this.descriptions = descriptions; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + +} diff --git a/opensrp-common/src/main/java/org/opensrp/common/AllConstants.java b/opensrp-common/src/main/java/org/opensrp/common/AllConstants.java index 902b3f827f..b022f8fac1 100644 --- a/opensrp-common/src/main/java/org/opensrp/common/AllConstants.java +++ b/opensrp-common/src/main/java/org/opensrp/common/AllConstants.java @@ -5,6 +5,14 @@ public class AllConstants { public static final String OPENSRP_FORM_DATABASE_CONNECTOR = "opensrpFormDatabaseConnector"; public static final String OPENSRP_DATABASE_CONNECTOR = "opensrpDatabaseConnector"; + public static final String CLIENT_DATABASE_CONNECTOR = "clientDatabaseConnector"; + public static final String EVENT_DATABASE_CONNECTOR = "eventDatabaseConnector"; + public static final String ALERT_DATABASE_CONNECTOR = "alertDatabaseConnector"; + public static final String ACTION_DATABASE_CONNECTOR = "actionDatabaseConnector"; + public static final String DRUG_ORDER_DATABASE_CONNECTOR = "drugorderDatabaseConnector"; + public static final String LOCATION_DATABASE_CONNECTOR = "locationDatabaseConnector"; + public static final String MULTIMEDIA_DATABASE_CONNECTOR = "multimediaDatabaseConnector"; + public static final String PROVIDER_DATABASE_CONNECTOR = "providerDatabaseConnector"; public static final String OPENSRP_MCTS_DATABASE_CONNECTOR = "opensrpMCTSDatabaseConnector"; public static final String SPACE = " "; public static final String BOOLEAN_TRUE_VALUE = "true"; @@ -33,7 +41,21 @@ public static class BaseEntity{ public static final String LAST_UPDATE = "lastEdited"; } - + public static class MultimediaData { + public static final String BASEENTITYID="baseEntityId"; + public static final String NAME="name"; + public static final String PROVIDERID="providerId"; + public static final String CONTENTTYPE="contentType"; + public static final String FILEPATH="fileType"; + public static final String FILECATEGORY="fileCategory"; + public static final String UPLOADDATE="uploadDate"; + public static final String DESCRIPTION="description"; + public static final String FILESIZE="fileSize"; + public static final String IMAGE="image"; + public static final String PREVIEWIMAGE="previewImage"; + public static final String COMMENTS="comments"; + } + public static class Client extends BaseEntity{ public static final String FIRST_NAME = "firstName"; public static final String MIDDLE_NAME = "middleName"; @@ -64,6 +86,47 @@ public static class Form { public static final String CLIENT_VERSION = "clientVersion"; public static final String SERVER_VERSION = "serverVersion"; } + + public static class Drug extends BaseEntity{ + public static final String NAME="name"; + public static final String NAMEUUID="nameUuid"; + public static final String BASENAME="baseName"; + public static final String BASENAMEUUID="baseNameUuid"; + public static final String CREATOR="creator"; + public static final String CREATORUUID="creatorUuid"; + public static final String DOSESTRENGHT="doseStrenght"; + public static final String ROUTE="route"; + public static final String MAXDAILYDOSE="maxDailyDose"; + public static final String MINIDAILYDOSE="miniDailyDose"; + public static final String DESCRIPTION="Description"; + public static final String COMBINATION="combination"; + } + + public static class DrugOrder extends BaseEntity{ + public static final String orderType="orderType"; + public static final String drugName="drugName"; + public static final String orderNumber="orderNumber"; + public static final String patientUuid="patientUuid"; + public static final String drugUuid="drugUuid"; + public static final String action="action"; + public static final String careSettingUuid="careSettingUuid"; + public static final String previousOrder="previousOrder"; + public static final String dateActivated="dateActivated"; + public static final String dateStopped="dateStopped"; + public static final String autoExpireDate="autoExpireDate"; + public static final String encounterUuid="encounterUuid"; + public static final String ordererUuid="ordererUuid"; + public static final String urgency="urgency"; + public static final String instructions="urgency"; + public static final String orderReason="orderReason"; + public static final String dosingType="dosingType"; + public static final String dose="dose"; + public static final String doseUnitsUuid="doseUnitsUuid"; + public static final String descriptions="descriptions"; + public static final String drugFrequencyUuid="drugFrequencyUuid"; + public static final String quantity="quantity"; + } + public static class HTTP { public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin"; public static final String WWW_AUTHENTICATE_HEADER = "www-authenticate"; diff --git a/opensrp-common/src/main/java/org/opensrp/common/FormEntityConstants.java b/opensrp-common/src/main/java/org/opensrp/common/FormEntityConstants.java index dba9904989..b9df8b30a0 100644 --- a/opensrp-common/src/main/java/org/opensrp/common/FormEntityConstants.java +++ b/opensrp-common/src/main/java/org/opensrp/common/FormEntityConstants.java @@ -58,4 +58,14 @@ public enum Encounter implements FormEntity{ public String entity(){return "encounter";} public String entityId(){return this.name();} } + + public enum PersonRelationship implements FormEntity{ + relationship_type, + person_b, + start_date, + end_date; + + public String entity(){return "person_relationship";} + public String entityId(){return this.name();} + } } \ No newline at end of file diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/DrugOrderAtomfeed.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/DrugOrderAtomfeed.java new file mode 100644 index 0000000000..9702174640 --- /dev/null +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/DrugOrderAtomfeed.java @@ -0,0 +1,114 @@ +package org.opensrp.connector.openmrs; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.UUID; +import java.util.logging.Logger; + +import org.apache.commons.lang3.StringUtils; +import org.ict4h.atomfeed.client.AtomFeedProperties; +import org.ict4h.atomfeed.client.domain.Event; +import org.ict4h.atomfeed.client.repository.AllFailedEvents; +import org.ict4h.atomfeed.client.repository.AllFeeds; +import org.ict4h.atomfeed.client.repository.AllMarkers; +import org.ict4h.atomfeed.client.service.AtomFeedClient; +import org.ict4h.atomfeed.client.service.EventWorker; +import org.ict4h.atomfeed.transaction.AFTransactionManager; +import org.ict4h.atomfeed.transaction.AFTransactionWork; +import org.json.JSONException; +import org.json.JSONObject; +import org.opensrp.connector.atomfeed.AtomfeedService; +import org.opensrp.connector.openmrs.constants.OpenmrsConstants; +import org.opensrp.connector.openmrs.service.OpenmrsOrderService; +import org.opensrp.connector.openmrs.service.OpenmrsService; +import org.opensrp.connector.openmrs.service.PatientService; +import org.opensrp.domain.Client; +import org.opensrp.domain.Drug; +import org.opensrp.domain.DrugOrder; +import org.opensrp.repository.AllDrugOrders; +import org.opensrp.service.ClientService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class DrugOrderAtomfeed extends OpenmrsService implements EventWorker, AtomfeedService +{ + private Logger log = Logger.getLogger(getClass().getSimpleName()); + public static final String CATEGORY_URL = "/OpenSRP_DrugOrder/recent.form"; + + private AtomFeedProperties atomFeedProperties; + private AFTransactionManager transactionManager; + private AtomFeedClient client; + + private OpenmrsOrderService orderService; + private AllDrugOrders allDrugOrders; + + @Autowired + public DrugOrderAtomfeed(AllMarkers allMarkers, AllFailedEvents allFailedEvents, + @Value("#{opensrp['openmrs.url']}") String baseUrl, + OpenmrsOrderService orderService, AllDrugOrders allDrugOrders) throws URISyntaxException { + if(baseUrl != null){ + OPENMRS_BASE_URL = baseUrl; + } + + this.atomFeedProperties = new AtomFeedProperties(); + this.transactionManager = new AFTransactionManager(){ + @Override + public T executeWithTransaction(AFTransactionWork action) throws RuntimeException { + return action.execute(); + } + }; + WebClient webClient = new WebClient(); + + URI uri = new URI(OPENMRS_BASE_URL+OpenmrsConstants.ATOMFEED_URL+CATEGORY_URL); + this.client = new AtomFeedClient(new AllFeeds(webClient), allMarkers, allFailedEvents, atomFeedProperties, transactionManager, uri, this); + + this.orderService = orderService; + this.allDrugOrders = allDrugOrders; + } + + @Override + public void process(Event event) { + log.info("Processing item : "+event.getContent()); + try { + String content = event.getContent().substring(event.getContent().lastIndexOf("/")+1); + JSONObject o = orderService.getDrugOrder(content); + if(o == null){ + throw new RuntimeException("DrugOrder uuid specified in atomfeed content ("+content+") did not return any drug order."); + } + DrugOrder drugO = orderService.toDrugOrder(o); + List existingL = allDrugOrders.findAllByCode(content); + if(existingL.isEmpty()){ + allDrugOrders.add(drugO); + } + else { + allDrugOrders.merge(existingL.get(0).getId(), drugO); + } + } catch (JSONException e) { + throw new RuntimeException(e); + } + } + + @Override + public void cleanUp(Event event) { + // TODO Auto-generated method stub + + } + + @Override + public void processEvents() { + Logger.getLogger(getClass().getName()).info("Processing PatientAtomfeeds"); + client.processEvents(); + } + + @Override + public void processFailedEvents() { + client.processFailedEvents(); + } + + void setUrl(String url) { + OPENMRS_BASE_URL = url; + } +} \ No newline at end of file diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java index 27561fe9b2..f455512028 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/constants/OpenmrsConstants.java @@ -10,6 +10,7 @@ public class OpenmrsConstants { public static final String SCHEDULER_OPENMRS_ATOMFEED_SYNCER_SUBJECT = "OpenMRS Atomfeed Syncer"; public static final String ENROLLMENT_TRACK_UUID = "openmrsTrackUuid"; public static final String SCHEDULER_OPENMRS_DATA_PUSH_SUBJECT = "OpenMRS Data Pusher"; + public static final String SCHEDULER_OPENMRS_DATA_PULL_SUBJECT = "OpenMRS Data Puller"; public static final String ATOMFEED_URL = "ws/atomfeed"; public static final String ATOMFEED_DATABASE_CONNECTOR = "atomfeedDatabaseConnector"; @@ -22,6 +23,8 @@ public enum SchedulerConfig { openmrs_syncer_sync_client_by_date_voided, openmrs_syncer_sync_event_by_date_updated, openmrs_syncer_sync_event_by_date_voided, + openmrs_syncer_sync_drugs, + openmrs_syncer_sync_orders, openmrs_syncer_sync_status, openmrs_syncer_sync_timestamp } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsAtomfeedListener.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsAtomfeedListener.java index df2b27754b..80a6d40312 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsAtomfeedListener.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsAtomfeedListener.java @@ -4,6 +4,7 @@ import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.server.event.annotations.MotechListener; +import org.opensrp.connector.openmrs.DrugOrderAtomfeed; import org.opensrp.connector.openmrs.EncounterAtomfeed; import org.opensrp.connector.openmrs.PatientAtomfeed; import org.opensrp.connector.openmrs.constants.OpenmrsConstants; @@ -15,24 +16,39 @@ public class OpenmrsAtomfeedListener { Logger log = Logger.getLogger(getClass().getName()); private PatientAtomfeed patientAtomfeed; private EncounterAtomfeed encounterAtomfeed; - + private DrugOrderAtomfeed drugOrderAtomfeed; + @Autowired - public OpenmrsAtomfeedListener(PatientAtomfeed patientAtomfeed, EncounterAtomfeed encounterAtomfeed) { + public OpenmrsAtomfeedListener(PatientAtomfeed patientAtomfeed, EncounterAtomfeed encounterAtomfeed, + DrugOrderAtomfeed drugOrderAtomfeed) { this.patientAtomfeed = patientAtomfeed; this.encounterAtomfeed = encounterAtomfeed; + this.drugOrderAtomfeed = drugOrderAtomfeed; } @MotechListener(subjects=OpenmrsConstants.SCHEDULER_OPENMRS_ATOMFEED_SYNCER_SUBJECT) public void syncAtomfeeds(MotechEvent event) { + log.info("Running "+OpenmrsConstants.SCHEDULER_OPENMRS_ATOMFEED_SYNCER_SUBJECT); try{ - log.info("Running "+OpenmrsConstants.SCHEDULER_OPENMRS_ATOMFEED_SYNCER_SUBJECT); patientAtomfeed.processEvents(); - + } + catch(Exception e){ + e.printStackTrace(); + } + + try{ encounterAtomfeed.processEvents(); } catch(Exception e){ e.printStackTrace(); } + + try{ + drugOrderAtomfeed.processEvents(); + } + catch(Exception e){ + e.printStackTrace(); + } } } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java index c823a421c4..7b84cd2210 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/schedule/OpenmrsSyncerListener.java @@ -1,10 +1,12 @@ package org.opensrp.connector.openmrs.schedule; +import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang3.exception.ExceptionUtils; import org.joda.time.DateTime; +import org.json.JSONArray; import org.json.JSONObject; import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.scheduletracking.api.domain.Enrollment; @@ -13,10 +15,13 @@ import org.opensrp.connector.openmrs.constants.OpenmrsConstants.SchedulerConfig; import org.opensrp.connector.openmrs.service.EncounterService; import org.opensrp.connector.openmrs.service.OpenmrsSchedulerService; +import org.opensrp.connector.openmrs.service.OpenmrsOrderService; import org.opensrp.connector.openmrs.service.PatientService; import org.opensrp.domain.AppStateToken; import org.opensrp.domain.Client; +import org.opensrp.domain.Drug; import org.opensrp.domain.Event; +import org.opensrp.repository.AllDrugs; import org.opensrp.scheduler.service.ActionService; import org.opensrp.scheduler.service.ScheduleService; import org.opensrp.service.ClientService; @@ -38,13 +43,16 @@ public class OpenmrsSyncerListener { private EncounterService encounterService; private EventService eventService; private ClientService clientService; + private OpenmrsOrderService openmrsOrderService; + private AllDrugs allDrugs; @Autowired public OpenmrsSyncerListener(OpenmrsSchedulerService openmrsSchedulerService, ScheduleService opensrpScheduleService, ActionService actionService, ConfigService config, ErrorTraceService errorTraceService, PatientService patientService, EncounterService encounterService, - ClientService clientService, EventService eventService) { + OpenmrsOrderService openmrsOrderService, + ClientService clientService, EventService eventService, AllDrugs allDrugs) { this.openmrsSchedulerService = openmrsSchedulerService; this.opensrpScheduleService = opensrpScheduleService; this.actionService = actionService; @@ -52,8 +60,10 @@ public OpenmrsSyncerListener(OpenmrsSchedulerService openmrsSchedulerService, this.errorTraceService = errorTraceService; this.patientService = patientService; this.encounterService = encounterService; + this.openmrsOrderService = openmrsOrderService; this.eventService = eventService; this.clientService = clientService; + this.allDrugs = allDrugs; this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_schedule_tracker_by_last_update_enrollment, 0, "ScheduleTracker token to keep track of enrollment synced with OpenMRS", true); @@ -69,6 +79,8 @@ public OpenmrsSyncerListener(OpenmrsSchedulerService openmrsSchedulerService, this.config.registerAppStateToken(SchedulerConfig.openmrs_syncer_sync_event_by_date_voided, 0, "OpenMRS data pusher token to keep track of voided events synced with OpenMRS", true); + + } @MotechListener(subjects = OpenmrsConstants.SCHEDULER_TRACKER_SYNCER_SUBJECT) @@ -177,4 +189,44 @@ public void pushToOpenMRS(MotechEvent event) { ex.printStackTrace(); } } + + @MotechListener(subjects = OpenmrsConstants.SCHEDULER_OPENMRS_DATA_PULL_SUBJECT) + public void pullDataFromOpenMRS(MotechEvent event) { + try { + System.out.println("RUNNING "+event.getSubject()); + JSONArray jdrugList = openmrsOrderService.getAllDrugs(); + for (int i = 0; i < jdrugList.length(); i++) { + JSONObject jdrug = jdrugList.getJSONObject(i); + try{ + List existingL = allDrugs.findAllByCode(jdrug.getString("uuid")); + if(existingL.isEmpty()){ + existingL = allDrugs.findAllByName(jdrug.getString("name")); + } + + Drug existingDrug= null; + if(existingL.isEmpty() == false){ + existingDrug = existingL.get(0); + } + Drug fetchedDrug = OpenmrsOrderService.toDrug(jdrug); + if(existingDrug == null){ + allDrugs.add(fetchedDrug); + } + else { + DateTime existingEdited = existingDrug.getDateEdited()==null?existingDrug.getDateCreated():existingDrug.getDateEdited(); + DateTime fetchedEdited = fetchedDrug.getDateEdited()==null?fetchedDrug.getDateCreated():fetchedDrug.getDateEdited(); + if(fetchedEdited.isAfter(existingEdited)){ + allDrugs.update(fetchedDrug); + } + } + } + catch(Exception e){ + e.printStackTrace(); + errorTraceService.log("OPENMRS FAILED DRUG PULL", Drug.class.getName(), jdrug.toString(), ExceptionUtils.getStackTrace(e), ""); + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java index f18a8b83eb..8a8e21cf82 100644 --- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/HouseholdService.java @@ -43,6 +43,14 @@ public JSONObject createRelationshipType(String AIsToB, String BIsToA, String de return new JSONObject(HttpUtil.post(getURL()+"/"+RELATIONSHIP_TYPE_URL, "", o.toString(), OPENMRS_USER, OPENMRS_PWD).body()); } + public JSONObject getRelationship(String clientUuid, String relationshipInWord, String relativeUuid) throws JSONException + { + JSONArray r = new JSONObject(HttpUtil.get(getURL() + +"/"+RELATIONSHIP_URL, "v=full&relation="+relationshipInWord+""+"&personA="+clientUuid+"&personB="+relativeUuid, OPENMRS_USER, OPENMRS_PWD).body()) + .getJSONArray("results"); + return r.length()>0?r.getJSONObject(0):null; + } + public JSONObject createRelationship(String clientUuid, String isARelationship, String relativeUuid) throws JSONException{ JSONObject o = convertRelationshipToOpenmrsJson(clientUuid, isARelationship, relativeUuid); return new JSONObject(HttpUtil.post(getURL()+"/"+RELATIONSHIP_URL, "", o.toString(), OPENMRS_USER, OPENMRS_PWD).body()); @@ -90,7 +98,6 @@ public void saveHH(OpenmrsHouseHold household, boolean ignoreExisting) throws JS JSONObject mp = ignoreExisting&&hhMemEx!=null?hhMemEx:patientService.createPatient(m.getClient()); JSONObject me = encounterService.createEncounter(m.getEvent().get(0)); - createRelationship(hhp.getString("uuid"), hhrel, mp.getString("uuid")); } } diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsOrderService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsOrderService.java new file mode 100644 index 0000000000..5f4ae8bfd9 --- /dev/null +++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/OpenmrsOrderService.java @@ -0,0 +1,194 @@ +package org.opensrp.connector.openmrs.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.joda.time.DateTime; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.opensrp.common.util.HttpUtil; +import org.opensrp.domain.*; +import org.opensrp.repository.AllDrugs; +import org.opensrp.repository.AllDrugOrders; +import org.opensrp.service.ClientService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + + +@Service +public class OpenmrsOrderService extends OpenmrsService{ + private static final String ORDER_URL = "ws/rest/v1/order"; + private static final String ORDER_TYPE_URL = "ws/rest/v1/ordertype"; + private static final String USER_URL = "ws/rest/v1/user"; + private static final String DRUG_URL = "ws/rest/v1/drug"; + public static final String OPENMRS_UUID_IDENTIFIER_TYPE = "OPENMRS_UUID"; + + private ClientService clientService; + private AllDrugs allDrugs; + + public OpenmrsOrderService() { + + } + + public OpenmrsOrderService(String openmrsUrl, String user, String password) { + super(openmrsUrl, user, password); + } + + public OpenmrsOrderService(ClientService clientService, AllDrugs allDrugs) { + this.clientService = clientService; + this.allDrugs = allDrugs; + } + public JSONObject getDrug(String uuid) throws JSONException + { + return new JSONObject(HttpUtil.get(getURL()+"/"+DRUG_URL+"/"+uuid, "v=full", OPENMRS_USER, OPENMRS_PWD).body()); + } + + public JSONArray getAllDrugs() throws JSONException + { + JSONArray res = new JSONObject(HttpUtil.get(getURL()+"/"+DRUG_URL, "v=full", OPENMRS_USER, OPENMRS_PWD).body()).getJSONArray("results"); + return res; + } + + public JSONObject getDrugOrder(String uuid) throws JSONException + { + JSONObject jsonObject=new JSONObject(HttpUtil.get(getURL()+"/"+ORDER_URL+"/"+uuid, "v=full", OPENMRS_USER, OPENMRS_PWD).body()); + return jsonObject; + } + + public static Drug toDrug(JSONObject drug) throws JSONException + { + String drugUuid = drug.getString("uuid"); + String drugName = drug.getString("name"); + + String conceptName = null; + String conceptUuid = null; + if(drug.has("concept")){ + JSONObject c = drug.getJSONObject("concept"); + conceptName = c.getString("display"); + conceptUuid = c.getString("uuid"); + } + + String dosageForm = null; + String dosageFormUuid = null; + if(drug.has("dosageForm")){ + JSONObject dc = drug.getJSONObject("dosageForm"); + dosageForm = dc.getString("display"); + dosageFormUuid = dc.getString("uuid"); + } + + String strength = drug.getString("doseStrength"); + String mini = drug.getString("minimumDailyDose"); + String max = drug.getString("maximumDailyDose"); + String description = drug.getString("description"); + String units = drug.getString("units"); + String combination = drug.getString("combination"); + + String route = null; + String routeUuid = null; + if(drug.has("route")){ + JSONObject r = drug.getJSONObject("dosageForm"); + route = r.getString("display"); + routeUuid = r.getString("uuid"); + } + + Map codes= new HashMap<>(); + codes.put("openmrs_uuid", drugUuid); + codes.put("openmrs_concept_uuid", conceptUuid); + codes.put("openmrs_route_uuid", routeUuid); + codes.put("openmrs_dosage_form_uuid", dosageFormUuid); + + Drug d = new Drug(drugName, conceptName, codes, route, dosageForm, strength, units, max, mini, description, combination); + if(drug.has("retired")){ + d.setVoided(drug.getBoolean("retired")); + } + + if(drug.has("auditInfo")){ + JSONObject audit = drug.getJSONObject("auditInfo"); + d.setCreator(new User(audit.getJSONObject("creator").getString("uuid"), + audit.getJSONObject("creator").getString("display"), null, null)); + d.setDateCreated(DateTime.parse(audit.getString("dateCreated"))); + if(audit.has("dateChanged")){ + d.setEditor(new User(audit.getJSONObject("changedBy").getString("uuid"), + audit.getJSONObject("changedBy").getString("display"), null, null)); + d.setDateEdited(DateTime.parse(audit.getString("dateChanged"))); + } + } + return d; + } + + public DrugOrder toDrugOrder(JSONObject drugOrder) throws JSONException + { + Map codes = new HashMap(); + + codes.put("openmrs_uuid", drugOrder.getString("uuid")); + + String patientUuid = drugOrder.getJSONObject("patient").getString("uuid"); + List cl = clientService.findAllByIdentifier(patientUuid); + String baseEntityId = cl.size()>0?cl.get(0).getBaseEntityId():null; + if(baseEntityId == null){ + throw new IllegalAccessError("Patient was not found in opensrp while importing drug order "+drugOrder); + } + + codes.put("openmrs_patient_uuid", patientUuid); + + String drugUuid = drugOrder.getJSONObject("drug").getString("uuid"); + List drugL = allDrugs.findAllByCode(drugUuid); + String drugId = drugL.size()>0?drugL.get(0).getId():null; + if(drugId == null){ + throw new IllegalAccessError("Drug was not found in opensrp while importing drug order "+drugOrder); + } + codes.put("openmrs_drug_uuid", drugUuid); + + DateTime dateActivated = null; + if(drugOrder.has("dateActivated")){ + dateActivated = DateTime.parse(drugOrder.getString("dateActivated")); + } + DateTime autoExpireDate = null; + if(drugOrder.has("autoExpireDate")){ + autoExpireDate = DateTime.parse(drugOrder.getString("autoExpireDate")); + } + + String frequency = null; + if(drugOrder.has("frequency")){ + frequency = drugOrder.getJSONObject("frequency").getString("display"); + } + + String quantity = drugOrder.has("quantity")?drugOrder.getString("quantity"):null; + String quantityUnits = null; + if(drugOrder.has("quantityUnits")){ + quantityUnits = drugOrder.getJSONObject("quantityUnits").getString("display"); + } + + String orderNumber = drugOrder.getString("orderNumber"); + String action = drugOrder.getString("action"); + String urgency = drugOrder.getString("urgency"); + String instructions = drugOrder.getString("instructions"); + + String drugName = drugOrder.getString("display"); + String dose = drugOrder.getString("dose"); + String discontinuedBy = drugOrder.has("discontinuedBy")?drugOrder.getString("discontinuedBy"):null; + DateTime discontinuedDate = null; + if(drugOrder.has("discontinuedDate")){ + discontinuedDate = DateTime.parse(drugOrder.getString("discontinuedDate")); + } + String discontinuedReason = drugOrder.has("discontinuedReason")?drugOrder.getString("discontinuedReason"):null; + + String orderReason = drugOrder.getString("orderReason"); + String orderer = drugOrder.getString("orderer"); + + String route = null; + if(drugOrder.has("route")){ + route = drugOrder.getJSONObject("route").getString("display"); + } + + DrugOrder drugOrderO = new DrugOrder(baseEntityId, drugOrder.getString("type"), drugId, codes, + dateActivated, autoExpireDate, frequency, quantity, quantityUnits, orderNumber, action, + urgency, instructions, dose, null, null, discontinuedBy , discontinuedDate, discontinuedReason, + orderReason, orderer, route, null); + return drugOrderO; + } +} diff --git a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/EncounterTest.java b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/EncounterTest.java index d7756a48b0..5f40ed03e1 100644 --- a/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/EncounterTest.java +++ b/opensrp-connector/src/test/java/org/opensrp/connector/openmrs/service/EncounterTest.java @@ -82,6 +82,34 @@ public void testEncounter() throws JSONException, ParseException, IOException { } } + + @Test + public void relationshipTest() throws JSONException, ParseException, IOException { + final FormSubmission fs = getFormSubmissionFor("new_member_registration"); + final Client c = oc.getClientFromFormSubmission(fs); + System.out.print(c); + if(pushToOpenmrsForTest){ + System.out.println(ps.getPatientByIdentifier(c.getBaseEntityId())); + JSONObject p = ps.getPatientByIdentifier(c.getBaseEntityId()); + if(p == null){ + p = ps.createPatient(c); + } + final JSONObject relationShipJSON=hhs.getRelationshipType(c.getRelationships().get(0).getRelationship()); + final String relationShipUUID=relationShipJSON.getString("uuid"); + JSONObject o=hhs.getRelationship(p.getString("uuid"),c.getRelationships().get(0).getRelationship(),c.getRelationships().get(0).getPerson_b()); + System.out.println("Before If: "+ o); + if(o==null) + { + o= hhs.createRelationship(p.getString("uuid"), relationShipUUID,c.getRelationships().get(0).getPerson_b()); + System.out.println("JsonObject: "+ o); + return; + } + System.out.println("RelationShip UUID: "+ o.getString("uuid")); + } + } + + + @Ignore @Test public void testGroupedEncounter() throws JSONException, ParseException, IOException { FormSubmission fs = getFormSubmissionFor("repeatform"); diff --git a/opensrp-connector/src/test/resources/form/new_member_registration/form.json b/opensrp-connector/src/test/resources/form/new_member_registration/form.json new file mode 100644 index 0000000000..a84ef848d5 --- /dev/null +++ b/opensrp-connector/src/test/resources/form/new_member_registration/form.json @@ -0,0 +1 @@ +{"name":"woman_tt_enrollement_test_form","title":"خواتین انرولمنٹ فارم برائے ٹی ٹی ٹیکاجات - Woman TT Enrollment Form","sms_keyword":"woman_tt_enrollement_test_form","default_language":"English","instance":{"encounter_type":"Woman TT enrollment"},"version":"201609281042","id_string":"woman_tt_enrollement_test_form","type":"survey","children":[{"type":"hidden","name":"provider_uc"},{"type":"hidden","name":"provider_town"},{"type":"hidden","name":"provider_city"},{"type":"hidden","name":"provider_province"},{"instance":{"openmrs_entity_id":"location_id","openmrs_entity":"encounter"},"type":"hidden","name":"provider_id"},{"instance":{"openmrs_entity_id":"Program Client ID","openmrs_entity":"person_identifier"},"type":"hidden","name":"provider_location_id"},{"type":"hidden","name":"existing_program_client_id"},{"type":"hidden","name":"provider_location_name"},{"type":"note","name":"provider_location_note","label":{"Roman Urdu":"Shehr: ${provider_city} ; Town: ${provider_town} ; UC: ${provider_uc} ; Center ka naam: ${provider_location_name}","English":"City: ${provider_city} ; Town: ${provider_town} ; UC: ${provider_uc} ; Center Name: ${provider_location_name}"}},{"instance":{"openmrs_entity_id":"163138AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"start","name":"start"},{"instance":{"openmrs_entity_id":"encounter_date","openmrs_entity":"encounter"},"type":"end","name":"end"},{"instance":{"openmrs_entity_id":"163149AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"today","name":"today"},{"instance":{"openmrs_entity_id":"163150AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"deviceid","name":"deviceid"},{"instance":{"openmrs_entity_id":"163151AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"subscriberid","name":"subscriberid"},{"instance":{"openmrs_entity_id":"163152AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"simserial","name":"simserial"},{"type":"phonenumber","name":"phonenumber"},{"bind":{"required":"yes"},"type":"note","name":"program_client_id","label":{"Roman Urdu":"Program ID: ${existing_program_client_id}","English":"Program ID: ${existing_program_client_id}"}},{"bind":{"calculate":"${today}"},"type":"calculate","instance":{"openmrs_entity_id":"EPI Card Number","openmrs_entity":"person_attribute"},"name":"client_reg_date","label":{"English":"client_reg_date"}},{"bind":{"jr:constraintMsg":{"Roman Urdu":"Number 8 hindason par mushtamil hona chahiye","English":"Number should be 8 digits"},"required":"yes","constraint":"string-length(.) = 8"},"type":"integer","instance":{"openmrs_entity_id":"first_name","openmrs_entity":"person"},"name":"epi_card_number","label":{"Roman Urdu":"EPI Card Number","English":"EPI Card Number:"}},{"bind":{"jr:constraintMsg":{"Roman Urdu":"Darj karda maaloomaat durust nahi","English":"Invalid data entered"},"required":"yes","constraint":"regex(., '^[a-zA-Z\\s\\.\\-]{3,25}$')"},"type":"text","name":"first_name","label":{"English":"Name","Roman Urdu":"Naam"}},{"name":"birth_date_known","default":"yes","bind":{"required":"yes"},"label":{"English":"Is birthdate known?","Roman Urdu":"Kya tareekh-e-pedaaish maloom hai?"},"type":"select one","children":[{"instance":{"openmrs_code":"1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"yes","label":{"Roman Urdu":"Yes","English":"Yes"}},{"instance":{"openmrs_code":"1066AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"no","label":{"Roman Urdu":"No","English":"No"}}]},{"bind":{"required":"yes","jr:constraintMsg":{"Roman Urdu":"Khatoon ki umar 15 saal ya zyada honi chahiyay","English":"Woman must be 15 years or above"},"relevant":"selected(${birth_date_known}, 'yes')","constraint":".<=(${today} - (15*365))"},"type":"date","name":"birth_date","label":{"English":"Birth date","Roman Urdu":"Tareekh-e-pedaaish"}},{"bind":{"required":"yes","jr:constraintMsg":{"Roman Urdu":"Khatoon ki umar 15 saal ya zyada honi chahiyay","English":"Woman must be 15 years or above"},"relevant":"selected(${birth_date_known}, 'no')","constraint":". >= 15"},"type":"integer","instance":{"openmrs_entity_id":"154384AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"name":"age","label":{"Roman Urdu":"Umar (saal)","English":"Age (years)"}},{"bind":{"calculate":"if(selected(${birth_date_known}, 'yes'), int((${today} - ${birth_date}) div 365), ${age})"},"type":"calculate","name":"calc_age"},{"bind":{"calculate":"format-date (date(${today} - int(${age} * 365.25)), '%Y-%m-%d')"},"type":"calculate","name":"calc_dob","instance":{"openmrs_entity_id":"birthdate","openmrs_entity":"person"}},{"bind":{"calculate":"if(${birth_date_known}='yes', ${birth_date}, ${calc_dob})"},"type":"calculate","name":"dob","instance":{"openmrs_entity_id":"birthdate_estimated","openmrs_entity":"person"}},{"bind":{"calculate":"if(${birth_date_known} = 'yes', '0', '1')"},"type":"calculate","name":"dob_estimated"},{"instance":{"openmrs_entity_id":"gender","openmrs_entity":"person"},"type":"note","name":"birth_date_note","label":{"Roman Urdu":"Tareekh-e-pedaaish: ${dob} (${calc_age} saal)","English":"Date of Birth: ${dob} (${calc_age} years)"}},{"name":"gender","default":"female","bind":{"required":"yes","calculate":"female"},"label":{"Roman Urdu":"Jins","English":"Gender"},"instance":{"openmrs_entity_id":"1594AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"calculate"},{"bind":{"jr:constraintMsg":{"Roman Urdu":"Darj karda maaloomaat durust nahi","English":"Invalid data entered"},"constraint":"regex(., '^[a-zA-Z\\s\\.\\-]{3,25}$')"},"type":"text","name":"father_name","label":{"English":"Father's Name","Roman Urdu":"Waalid ka naam"}},{"name":"marriage","bind":{"required":"yes"},"label":{"Roman Urdu":"Kya aap shaadi shuda hain?","English":"Are you married?"},"instance":{"openmrs_entity_id":"161135AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"},"type":"select one","children":[{"instance":{"openmrs_code":"1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"yes","label":{"Roman Urdu":"Yes","English":"Yes"}},{"instance":{"openmrs_code":"1066AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"no","label":{"Roman Urdu":"No","English":"No"}}]},{"bind":{"jr:constraintMsg":{"Roman Urdu":"Darj karda maaloomaat durust nahi","English":"Invalid data entered"},"relevant":"selected(${marriage}, 'yes')","constraint":"regex(., '^[a-zA-Z\\s\\.\\-]{3,25}$')"},"type":"text","instance":{"openmrs_entity_id":"last_name","openmrs_entity":"person"},"name":"husband_name","label":{"Roman Urdu":"Shohar ka naam","English":"Husband's Name"}},{"bind":{"calculate":"if(${marriage} = 'no', ${father_name}, ${husband_name})"},"type":"calculate","name":"last_name","instance":{"openmrs_entity_id":"163153AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity":"concept"}},{"control":{"appearance":"minimal"},"name":"ethnicity","bind":{"required":"yes"},"label":{"English":"Ethnicity","Roman Urdu":"Qomiat"},"instance":{"openmrs_entity":"concept","openmrs_entity_id":"160632AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","openmrs_entity_parent":"163330AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"type":"select one","children":[{"instance":{"openmrs_code":"163217AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"sindhi","label":{"Roman Urdu":"Sindhi","English":"Sindhi"}},{"instance":{"openmrs_code":"163219AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"muhajir","label":{"Roman Urdu":"Muhajir","English":"Muhajir"}},{"instance":{"openmrs_code":"163215AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"punjabi","label":{"Roman Urdu":"Punjabi","English":"Punjabi"}},{"instance":{"openmrs_code":"163216AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"pushtuns","label":{"Roman Urdu":"Pushtun","English":"Pushtun"}},{"instance":{"openmrs_code":"163218AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"saraiki","label":{"Roman Urdu":"Saraiki","English":"Saraiki"}},{"instance":{"openmrs_code":"163220AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"balochi","label":{"Roman Urdu":"Balochi","English":"Balochi"}},{"instance":{"openmrs_code":"5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"other","label":{"Roman Urdu":"Deegar","English":"Other"}}]},{"bind":{"relevant":"selected(${ethnicity}, 'other')"},"type":"text","instance":{"openmrs_entity":"person_address","openmrs_entity_id":"stateProvince","openmrs_entity_parent":"usual_residence"},"name":"ethnicity_other","label":{"English":"Please specify:","Roman Urdu":"Wazaahat karain"}},{"name":"reminders_approval","bind":{"required":"yes"},"label":{"English":"Are you willing to receive SMS reminders for your next visit?","Roman Urdu":"Kya aap apnay aglay doray ki yaad-dihani ke liye SMS mausool karna chahti hain?"},"instance":{"openmrs_entity":"person_address","openmrs_entity_id":"cityVillage","openmrs_entity_parent":"usual_residence"},"type":"select one","children":[{"instance":{"openmrs_code":"1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"yes","label":{"Roman Urdu":"Yes","English":"Yes"}},{"instance":{"openmrs_code":"1066AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"name":"no","label":{"Roman Urdu":"No","English":"No"}}]},{"bind":{"required":"yes","jr:constraintMsg":{"Roman Urdu":"Phone number 11 hindason par mushtamil aur mundarja zail shakal main hona chahiey: 03*********","English":"Phone number should be 11 digits in the following format: 03*********"},"relevant":"${reminders_approval}='yes'","constraint":"regex(., '^03[0-9]{9}$')"},"type":"text","name":"contact_phone_number","label":{"English":"Mobile Number:","Roman Urdu":"Mobile number:"}},{"instance":{"openmrs_entity":"person_relationship","openmrs_entity_id":"person_b","openmrs_entity_parent":"child"},"type":"text","name":"child_id","label":{"English":"child id to relate","Roman Urdu":"child id"}},{"instance":{"openmrs_entity":"person_relationship","openmrs_entity_id":"person_b","openmrs_entity_parent":"husband"},"type":"text","name":"husband_id","label":{"English":"husband id to relate","Roman Urdu":"husband id"}},{"control":{"bodyless":true},"type":"group","children":[{"bind":{"readonly":"true()","calculate":"concat('uuid:', uuid())"},"type":"calculate","name":"instanceID"}],"name":"meta"}]} \ No newline at end of file diff --git a/opensrp-connector/src/test/resources/form/new_member_registration/form.xml b/opensrp-connector/src/test/resources/form/new_member_registration/form.xml new file mode 100644 index 0000000000..d426861eb1 --- /dev/null +++ b/opensrp-connector/src/test/resources/form/new_member_registration/form.xml @@ -0,0 +1,219 @@ +
+ + +

خواتین انرولمنٹ فارم برائے ٹی ٹی ٹیکاجات - Woman TT Enrollment Form

+
+
+ + Kya tareekh-e-pedaaish maloom hai? + Is birthdate known? + * +
+ + +
+
+
+
+ + Kya aap shaadi shuda hain? + Are you married? + * +
+ + +
+
+
+
+ + Kya aap apnay aglay doray ki yaad-dihani ke liye SMS mausool karna chahti hain? + Are you willing to receive SMS reminders for your next visit? + * +
+ + +
+
+
+ +
diff --git a/opensrp-connector/src/test/resources/form/new_member_registration/form_definition.json b/opensrp-connector/src/test/resources/form/new_member_registration/form_definition.json new file mode 100644 index 0000000000..c9ff8eeb5d --- /dev/null +++ b/opensrp-connector/src/test/resources/form/new_member_registration/form_definition.json @@ -0,0 +1,137 @@ +{ + "form" : { + "bind_type" : "pkwoman", +"default_bind_path" : "/model/instance/woman_tt_enrollement_test_form/", + "fields" : [ { + "name" : "id", + "shouldLoadValue" : true + }, { + "name" : "provider_uc", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_uc" + }, { + "name" : "provider_town", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_town" + }, { + "name" : "provider_city", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_city" + }, { + "name" : "provider_province", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_province" + }, { + "name" : "provider_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_id" + }, { + "name" : "provider_location_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_location_id" + }, { + "name" : "existing_program_client_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/existing_program_client_id" + }, { + "name" : "provider_location_name", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_location_name" + }, { + "name" : "provider_location_note", + "bind" : "/model/instance/woman_tt_enrollement_test_form/provider_location_note" + }, { + "name" : "start", + "bind" : "/model/instance/woman_tt_enrollement_test_form/start" + }, { + "name" : "end", + "bind" : "/model/instance/woman_tt_enrollement_test_form/end" + }, { + "name" : "today", + "bind" : "/model/instance/woman_tt_enrollement_test_form/today" + }, { + "name" : "deviceid", + "bind" : "/model/instance/woman_tt_enrollement_test_form/deviceid" + }, { + "name" : "subscriberid", + "bind" : "/model/instance/woman_tt_enrollement_test_form/subscriberid" + }, { + "name" : "simserial", + "bind" : "/model/instance/woman_tt_enrollement_test_form/simserial" + }, { + "name" : "phonenumber", + "bind" : "/model/instance/woman_tt_enrollement_test_form/phonenumber" + }, { + "name" : "program_client_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/program_client_id" + }, { + "name" : "client_reg_date", + "bind" : "/model/instance/woman_tt_enrollement_test_form/client_reg_date" + }, { + "name" : "epi_card_number", + "bind" : "/model/instance/woman_tt_enrollement_test_form/epi_card_number" + }, { + "name" : "first_name", + "bind" : "/model/instance/woman_tt_enrollement_test_form/first_name" + }, { + "name" : "birth_date_known", + "bind" : "/model/instance/woman_tt_enrollement_test_form/birth_date_known" + }, { + "name" : "birth_date", + "bind" : "/model/instance/woman_tt_enrollement_test_form/birth_date" + }, { + "name" : "age", + "bind" : "/model/instance/woman_tt_enrollement_test_form/age" + }, { + "name" : "calc_age", + "bind" : "/model/instance/woman_tt_enrollement_test_form/calc_age" + }, { + "name" : "calc_dob", + "bind" : "/model/instance/woman_tt_enrollement_test_form/calc_dob" + }, { + "name" : "dob", + "bind" : "/model/instance/woman_tt_enrollement_test_form/dob" + }, { + "name" : "dob_estimated", + "bind" : "/model/instance/woman_tt_enrollement_test_form/dob_estimated" + }, { + "name" : "birth_date_note", + "bind" : "/model/instance/woman_tt_enrollement_test_form/birth_date_note" + }, { + "name" : "gender", + "bind" : "/model/instance/woman_tt_enrollement_test_form/gender" + }, { + "name" : "father_name", + "bind" : "/model/instance/woman_tt_enrollement_test_form/father_name" + }, { + "name" : "marriage", + "bind" : "/model/instance/woman_tt_enrollement_test_form/marriage" + }, { + "name" : "husband_name", + "bind" : "/model/instance/woman_tt_enrollement_test_form/husband_name" + }, { + "name" : "last_name", + "bind" : "/model/instance/woman_tt_enrollement_test_form/last_name" + }, { + "name" : "ethnicity", + "bind" : "/model/instance/woman_tt_enrollement_test_form/ethnicity" + }, { + "name" : "ethnicity_other", + "bind" : "/model/instance/woman_tt_enrollement_test_form/ethnicity_other" + }, { + "name" : "reminders_approval", + "bind" : "/model/instance/woman_tt_enrollement_test_form/reminders_approval" + }, { + "name" : "contact_phone_number", + "bind" : "/model/instance/woman_tt_enrollement_test_form/contact_phone_number" + }, { + "name" : "child_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/child_id" + }, { + "name" : "Relationship_type1", + "bind" : "/model/instance/woman_tt_enrollement_test_form/Relationship_type1" + }, { + "name" : "husband_id", + "bind" : "/model/instance/woman_tt_enrollement_test_form/husband_id" + }, { + "name" : "Relationship_type2", + "bind" : "/model/instance/woman_tt_enrollement_test_form/Relationship_type2" + }, { + "name" : "instanceID", + "bind" : "/model/instance/woman_tt_enrollement_test_form/meta/instanceID" + } ], + "sub_forms" : [ ] + } +} \ No newline at end of file diff --git a/opensrp-connector/src/test/resources/form/new_member_registration/form_submission.json b/opensrp-connector/src/test/resources/form/new_member_registration/form_submission.json new file mode 100644 index 0000000000..a7a2f5c6a7 --- /dev/null +++ b/opensrp-connector/src/test/resources/form/new_member_registration/form_submission.json @@ -0,0 +1,281 @@ +{ + "_id": "58e123cec0dc6b83cf04666bf6de20c5", + "_rev": "1-a68fc348e1a7ab4cfd6d8772484fd19c", + "type": "FormSubmission", + "anmId": "ahmed", + "instanceId": "e4a6d64f-c288-4423-89ca-d309aa2b2349", + "formName": "new_member_registration", + "entityId": "e8bb4a1b-1f3a-4f19-8f7f-8be826b1855d", + "clientVersion": 1475055151630, + "formDataDefinitionVersion": "3", + "formInstance": { + "form_data_definition_version": "3", + "form": { + "bind_type": "pkwoman", + "default_bind_path": "/model/instance/woman_tt_enrollement_test_form/", + "fields": [ + { + "name": "id", + "value": "e8bb4a1b-1f3a-4f19-8f7f-8be826b1855d", + "source": "pkwoman.id" + }, + { + "name": "provider_uc", + "value": "Zaman Town", + "source": "pkwoman.provider_uc" + }, + { + "name": "provider_town", + "value": "Korangi", + "source": "pkwoman.provider_town" + }, + { + "name": "provider_city", + "value": "Karachi", + "source": "pkwoman.provider_city" + }, + { + "name": "provider_province", + "value": "Sindh", + "source": "pkwoman.provider_province" + }, + { + "name": "provider_id", + "value": "ahmed", + "source": "pkwoman.provider_id" + }, + { + "name": "provider_location_id", + "value": "Homeopathic Center", + "source": "pkwoman.provider_location_id" + }, + { + "name": "existing_program_client_id", + "value": "218159972", + "source": "pkwoman.existing_program_client_id" + }, + { + "name": "provider_location_name", + "value": "Homeopathic Center", + "source": "pkwoman.provider_location_name" + }, + { + "name": "provider_location_note", + "value": "", + "source": "pkwoman.provider_location_note" + }, + { + "name": "start", + "value": "2016-09-28 14:32:00", + "source": "pkwoman.start" + }, + { + "name": "end", + "value": "2016-09-28 14:32:31", + "source": "pkwoman.end" + }, + { + "name": "today", + "value": "2016-09-28", + "source": "pkwoman.today" + }, + { + "name": "deviceid", + "value": "Error: could not determine deviceID", + "source": "pkwoman.deviceid" + }, + { + "name": "subscriberid", + "value": "no subscriberid property in enketo", + "source": "pkwoman.subscriberid" + }, + { + "name": "simserial", + "value": "no simserial property in enketo", + "source": "pkwoman.simserial" + }, + { + "name": "phonenumber", + "value": "no phonenumber property in enketo", + "source": "pkwoman.phonenumber" + }, + { + "name": "program_client_id", + "value": "218159972", + "source": "pkwoman.program_client_id" + }, + { + "name": "client_reg_date", + "value": "2016-09-28", + "source": "pkwoman.client_reg_date" + }, + { + "name": "epi_card_number", + "value": "20152580", + "source": "pkwoman.epi_card_number" + }, + { + "name": "first_name", + "value": "test lastDay", + "source": "pkwoman.first_name" + }, + { + "name": "birth_date_known", + "value": "no", + "source": "pkwoman.birth_date_known" + }, + { + "name": "birth_date", + "value": "", + "source": "pkwoman.birth_date" + }, + { + "name": "age", + "value": "25", + "source": "pkwoman.age" + }, + { + "name": "calc_age", + "value": "25", + "source": "pkwoman.calc_age" + }, + { + "name": "calc_dob", + "value": "1991-09-29", + "source": "pkwoman.calc_dob" + }, + { + "name": "dob", + "value": "1991-09-29", + "source": "pkwoman.dob" + }, + { + "name": "dob_estimated", + "value": "1", + "source": "pkwoman.dob_estimated" + }, + { + "name": "birth_date_note", + "value": "", + "source": "pkwoman.birth_date_note" + }, + { + "name": "gender", + "value": "male", + "source": "pkwoman.gender" + }, + { + "name": "father_name", + "value": "Fgy", + "source": "pkwoman.father_name" + }, + { + "name": "marriage", + "value": "no", + "source": "pkwoman.marriage" + }, + { + "name": "husband_name", + "value": "", + "source": "pkwoman.husband_name" + }, + { + "name": "last_name", + "value": "Fgy", + "source": "pkwoman.last_name" + }, + { + "name": "ethnicity", + "value": "punjabi", + "source": "pkwoman.ethnicity" + }, + { + "name": "ethnicity_other", + "value": "", + "source": "pkwoman.ethnicity_other" + }, + { + "name": "reminders_approval", + "value": "no", + "source": "pkwoman.reminders_approval" + }, + { + "name": "contact_phone_number", + "value": "", + "source": "pkwoman.contact_phone_number" + }, + { + "name": "husband_id", + "value": "007037a0-0500-11e3-8ffd-0800200c9a66", + "source": "pkwoman.husband_id" + }, + { + "name": "child_id", + "value": "007037a0-0500-11e3-8ffd-0800200c9a66", + "source": "pkwoman.child_id" + }, + { + "name": "Relation_type1", + "value": "father", + "source": "pkwoman.child.Relation_type" + }, + { + "name": "Relation_type2", + "value": "wife", + "source": "pkwoman.husband.Relation_type" + }, + { + "name": "instanceID", + "value": "uuid:267c7f9a-ad5e-4c69-9406-cca21af8ffe0", + "source": "pkwoman.instanceID" + } + ], + "fieldsAsMap": { + "contact_phone_number": "", + "program_client_id": "218158872", + "provider_id": "ahmed", + "instanceID": "uuid:267c7f9a-ad5e-4c69-9406-cca21af8ffe0", + "today": "2016-09-28", + "birth_date_note": "", + "father_name": "Fgy", + "deviceid": "Error: could not determine deviceID", + "id": "e8bb4a1b-1f3a-4f19-8f7f-8be826b1855d", + "client_reg_date": "2016-09-28", + "ethnicity_other": "", + "first_name": "Dghfd", + "husband_name": "", + "age": "25", + "gender": "", + "dob_estimated": "1", + "birth_date_known": "no", + "provider_location_id": "Homeopathic Center", + "provider_province": "Sindh", + "simserial": "no simserial property in enketo", + "end": "2016-09-28 14:32:31", + "phonenumber": "no phonenumber property in enketo", + "provider_location_name": "Homeopathic Center", + "birth_date": "", + "provider_uc": "Zaman Town", + "calc_dob": "1991-09-29", + "marriage": "no", + "existing_program_client_id": "218158872", + "calc_age": "25", + "provider_location_note": "", + "provider_city": "Karachi", + "subscriberid": "no subscriberid property in enketo", + "start": "2016-09-28 14:32:00", + "dob": "1991-09-29", + "last_name": "Fgy", + "provider_town": "Korangi", + "epi_card_number": "20152580", + "ethnicity": "punjabi", + "husband_id": "123456789", + "Relation_type1": "father", + "Relation_type2": "wife", + "child_id": "987654321", + "reminders_approval": "no" + } + } + }, + "serverVersion": 1475055131481 +} \ No newline at end of file diff --git a/opensrp-connector/src/test/resources/form/new_member_registration/model.xml b/opensrp-connector/src/test/resources/form/new_member_registration/model.xml new file mode 100644 index 0000000000..5090135b13 --- /dev/null +++ b/opensrp-connector/src/test/resources/form/new_member_registration/model.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + yes + + + + + + + + female + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-core/pom.xml b/opensrp-core/pom.xml index aa95cfa72a..06d7502e53 100644 --- a/opensrp-core/pom.xml +++ b/opensrp-core/pom.xml @@ -48,7 +48,118 @@ + + org.apache.pdfbox + pdfbox + 2.0.1 + + + + org.jcodec + jcodec-javase + 0.1.9 + + + org.bytedeco + javacpp + 1.2.1 + + + org.bytedeco.javacpp-presets + opencv + 3.1.0-1.2 + + + org.bytedeco.javacpp-presets + ffmpeg + 3.0.2-1.2 + + + org.bytedeco.javacpp-presets + flycapture + 2.9.3.43-1.2 + + + org.bytedeco.javacpp-presets + libdc1394 + 2.2.4-1.2 + + + org.bytedeco.javacpp-presets + libfreenect + 0.5.3-1.2 + + + org.bytedeco.javacpp-presets + videoinput + 0.200-1.2 + + + org.bytedeco.javacpp-presets + artoolkitplus + 2.3.1-1.2 + + + org.bytedeco.javacpp-presets + chilitags + master-1.2 + + org.bytedeco.javacpp-presets + flandmark + 1.07-1.2 + + + org.bytedeco.javacpp-presets + fftw + 3.3.4-1.2 + + + org.bytedeco.javacpp-presets + gsl + 2.1-1.2 + + + org.bytedeco.javacpp-presets + llvm + 3.8.0-1.2 + + + org.bytedeco.javacpp-presets + leptonica + 1.73-1.2 + + + org.bytedeco.javacpp-presets + tesseract + 3.04.01-1.2 + + + org.bytedeco.javacpp-presets + caffe + rc3-1.2 + + + org.bytedeco.javacpp-presets + cuda + 7.5-1.2 + + + org.bytedeco.javacpp-presets + mxnet + master-1.2 + + + org.bytedeco.javacpp-presets + tensorflow + 0.8.0-1.2 + + + org.bytedeco + javacv + 1.2 + + motech-platform-server-api org.motechproject ${motech.version} diff --git a/opensrp-core/src/main/java/org/opensrp/domain/BaseEntity.java b/opensrp-core/src/main/java/org/opensrp/domain/BaseEntity.java index 4f1ef28751..213efafe04 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/BaseEntity.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/BaseEntity.java @@ -14,7 +14,6 @@ import org.ektorp.support.TypeDiscriminator; @JsonIgnoreProperties(ignoreUnknown = true) -@TypeDiscriminator("doc.baseEntityId && doc.identifiers") public class BaseEntity extends BaseDataObject { @JsonProperty private String baseEntityId; diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Client.java b/opensrp-core/src/main/java/org/opensrp/domain/Client.java index 84f589bca4..030ad103ed 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/Client.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/Client.java @@ -1,10 +1,8 @@ package org.opensrp.domain; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; @@ -34,7 +32,7 @@ public class Client extends BaseEntity { @JsonProperty private String gender; @JsonProperty - private Map> relationships; + private List relationships; protected Client() { @@ -167,14 +165,21 @@ public void setGender(String gender) { this.gender = gender; } - public Map> getRelationships() { + public List getRelationships() { + if(relationships == null){ + relationships = new ArrayList<>(); + } return relationships; } - public void setRelationships(Map> relationships) { - this.relationships = relationships; + public void setRelationShip(List relationship) { + this.relationships = relationship; } - + + public void addRelationship(RelationShip relationship) { + addRelationship(relationship.getRelationship(), relationship.getPerson_b()); + } + public Client withFirstName(String firstName) { this.firstName = firstName; return this; @@ -223,42 +228,71 @@ public Client withGender(Gender gender) { /** * Overrides the existing data */ - public Client withRelationships(Map> relationships) { - this.relationships = relationships; + public Client withRelation(List relationShips) { + this.relationships = relationShips; return this; } - - public List findRelatives(String relationshipType) { + public Client withRelation(RelationShip relationship) { if(relationships == null){ - relationships = new HashMap<>(); + relationships = new ArrayList<>(); } + relationships.add(relationship); + return this; + } - return relationships.get(relationshipType); + public RelationShip findRelative(String relationshipType, String relativeId) { + if(relationships == null){ + relationships = new ArrayList<>(); + } + + for (RelationShip relationShip : relationships) { + if(relationShip.getRelationship().equalsIgnoreCase(relationshipType) + && relationShip.getPerson_b().equalsIgnoreCase(relativeId)){ + return relationShip; + } + } + return null; } - public void addRelationship(String relationType, String relativeEntityId) { + public List findRelations(String relativeId) { if(relationships == null){ - relationships = new HashMap<>(); + relationships = new ArrayList<>(); } - - List relatives = findRelatives(relationType); - if(relatives == null){ - relatives = new ArrayList<>(); + + List res = new ArrayList<>(); + for (RelationShip relationShip : relationships) { + if(relationShip.getPerson_b().equalsIgnoreCase(relativeId)){ + res.add(relationShip); + } } - relatives.add(relativeEntityId); - relationships.put(relationType, relatives); + return res; } - public List getRelationships(String relativeEntityId) { - List relations = new ArrayList(); - for (Entry> rl : relationships.entrySet()) { - if(rl.getValue().toString().equalsIgnoreCase(relativeEntityId)){ - relations.add(rl.getKey()); + public List findRelatives(String relationShip) { + if(relationships == null){ + relationships = new ArrayList<>(); + } + + List res = new ArrayList<>(); + for (RelationShip rel : relationships) { + if(rel.getRelationship().equalsIgnoreCase(relationShip)){ + res.add(rel); } } - return relations; + return res; } - + + public void addRelationship(String relationType, String relativeEntityId) { + if(relationships == null){ + relationships = new ArrayList<>(); + } + + RelationShip relative = findRelative(relationType, relativeEntityId); + if(relative == null){ + relationships.add(new RelationShip(relationType, relativeEntityId, null, null)); + } + } + @Override public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o, "id", "revision"); diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Drug.java b/opensrp-core/src/main/java/org/opensrp/domain/Drug.java new file mode 100644 index 0000000000..842e0e9346 --- /dev/null +++ b/opensrp-core/src/main/java/org/opensrp/domain/Drug.java @@ -0,0 +1,168 @@ +package org.opensrp.domain; + +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonProperty; +import org.ektorp.support.TypeDiscriminator; + +@TypeDiscriminator("doc.type === 'Drug'") +public class Drug extends BaseDataObject { + @JsonProperty + private String drugName; + @JsonProperty + private String drugBaseName; + @JsonProperty + private Map codes; + @JsonProperty + private String dosageForm; + @JsonProperty + private String route; + @JsonProperty + private String id; + @JsonProperty + private String doseStrength; + @JsonProperty + private String units; + @JsonProperty + private String maximumDailyDose; + @JsonProperty + private String minimumDailyDose; + @JsonProperty + private String description; + @JsonProperty + private String combination; + + protected Drug() { + + } + + public Drug(String baseEntityId) { + + } + public Drug(String drugName,String drugBaseName, Map codes, + String route, String dosageForm, String doseStrenght + , String units, String maxDailyDose,String miniDailyDose,String Description,String combination) { + this.drugName = drugName; + this.drugBaseName = drugBaseName; + this.codes = codes; + this.doseStrength = doseStrenght; + this.route = route; + this.dosageForm = dosageForm; + this.maximumDailyDose = maxDailyDose; + this.minimumDailyDose = miniDailyDose; + this.description = Description; + this.combination = combination; + } + @Override + public boolean equals(Object o) { + return EqualsBuilder.reflectionEquals(this, o); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this, "id"); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + public String getDrugName() { + return drugName; + } + + public void setDrugName(String drugName) { + this.drugName = drugName; + } + + public Map getCodes() { + return codes; + } + + public void setCodes(Map codes) { + this.codes = codes; + } + + public String getDosageForm() { + return dosageForm; + } + + public void setDosageForm(String dosageForm) { + this.dosageForm = dosageForm; + } + + public String getDrugBaseName() { + return drugBaseName; + } + + public void setDrugBaseName(String drugBaseName) { + this.drugBaseName = drugBaseName; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDoseStrength() { + return doseStrength; + } + + public void setDoseStrength(String doseStrength) { + this.doseStrength = doseStrength; + } + + public String getUnits() { + return units; + } + + public void setUnits(String units) { + this.units = units; + } + + public String getMaximumDailyDose() { + return maximumDailyDose; + } + + public void setMaximumDailyDose(String maximumDailyDose) { + this.maximumDailyDose = maximumDailyDose; + } + + public String getMinimumDailyDose() { + return minimumDailyDose; + } + + public void setMinimumDailyDose(String minimumDailyDose) { + this.minimumDailyDose = minimumDailyDose; + } + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCombination() { + return combination; + } + + public void setCombination(String combination) { + this.combination = combination; + } +} diff --git a/opensrp-core/src/main/java/org/opensrp/domain/DrugOrder.java b/opensrp-core/src/main/java/org/opensrp/domain/DrugOrder.java new file mode 100644 index 0000000000..cea8d3f078 --- /dev/null +++ b/opensrp-core/src/main/java/org/opensrp/domain/DrugOrder.java @@ -0,0 +1,309 @@ +package org.opensrp.domain; + +import java.util.Map; + +import org.codehaus.jackson.annotate.JsonProperty; +import org.ektorp.support.TypeDiscriminator; +import org.joda.time.DateTime; + +@TypeDiscriminator("doc.type == 'DrugOrder'") +public class DrugOrder extends BaseDataObject { + + @JsonProperty + private Map codes; + @JsonProperty + private String orderType; + @JsonProperty + private String drug; + @JsonProperty + private String orderNumber; + @JsonProperty + private String action; + @JsonProperty + private String previousOrder; + @JsonProperty + private DateTime dateActivated; + @JsonProperty + private String discontinuedBy; + @JsonProperty + private DateTime discontinuedDate; + @JsonProperty + private String discontinuedReason; + @JsonProperty + private DateTime autoExpireDate; + @JsonProperty + private String urgency; + @JsonProperty + private String instructions; + @JsonProperty + private String orderReason; + @JsonProperty + private String dosingType; + @JsonProperty + private String dose; + @JsonProperty + private String frequency; + @JsonProperty + private String descriptions; + @JsonProperty + private String quantity; + @JsonProperty + private String baseEntityId; + @JsonProperty + private String orderer; + @JsonProperty + private String route; + @JsonProperty + private String quantityUnits; + + public DrugOrder(String baseEntityId,String ordererName,String drug,String orderType, Map codes, + String orderNumber, String action, String previousOrder + , DateTime dateActivated, DateTime autoExpireDate,String urgency, + String instructions, String dosingType, String description,String quantity,String route, String quantityUnits) + { + this.baseEntityId=baseEntityId; + this.orderer=ordererName; + this.drug=drug; + this.orderType=orderType; + this.codes=codes; + this.orderNumber=orderNumber; + this.action=action; + this.previousOrder=previousOrder; + this.dateActivated=dateActivated; + this.autoExpireDate=autoExpireDate; + this.urgency=urgency; + this.instructions=instructions; + this.dosingType=dosingType; + this.descriptions=description; + this.quantity=quantity; + this.route=route; + this.quantityUnits=quantityUnits; + } + + public DrugOrder(String baseEntityId, String orderType, String drug, Map codes, + DateTime dateActivated, DateTime autoExpireDate, String frequency, String quantity, String quantityUnits, + String orderNumber, String action, String urgency, String instructions, String dose, String dosingType, + String previousOrder, String discontinuedBy, DateTime discontinuedDate, String discontinuedReason, + String orderReason, String orderer, String route, String descriptions) { + super(); + this.baseEntityId = baseEntityId; + this.orderType = orderType; + this.drug = drug; + this.codes = codes; + this.dateActivated = dateActivated; + this.autoExpireDate = autoExpireDate; + this.frequency = frequency; + this.quantity = quantity; + this.quantityUnits = quantityUnits; + this.orderNumber = orderNumber; + this.action = action; + this.urgency = urgency; + this.instructions = instructions; + this.dose = dose; + this.dosingType = dosingType; + this.previousOrder = previousOrder; + this.discontinuedBy = discontinuedBy; + this.discontinuedDate = discontinuedDate; + this.discontinuedReason = discontinuedReason; + this.orderReason = orderReason; + this.orderer = orderer; + this.route = route; + this.descriptions = descriptions; + } + + public DrugOrder() + { + + } + + public DrugOrder(String drug) + { + this.drug=drug; + } + public Map getCodes() { + return codes; + } + + public void setCodes(Map codes) { + this.codes = codes; + } + + + + public String getOrderType() { + return orderType; + } + + public void setOrderType(String orderType) { + this.orderType = orderType; + } + + public String getDrug() { + return drug; + } + + public void setDrug(String drug) { + this.drug = drug; + } + + public String getOrderNumber() { + return orderNumber; + } + + public void setOrderNumber(String orderNumber) { + this.orderNumber = orderNumber; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getPreviousOrder() { + return previousOrder; + } + + public void setPreviousOrder(String previousOrder) { + this.previousOrder = previousOrder; + } + + public DateTime getDateActivated() { + return dateActivated; + } + + public void setDateActivated(DateTime dateActivated) { + this.dateActivated = dateActivated; + } + + public DateTime getAutoExpireDate() { + return autoExpireDate; + } + + public void setAutoExpireDate(DateTime autoExpireDate) { + this.autoExpireDate = autoExpireDate; + } + + public String getUrgency() { + return urgency; + } + + public void setUrgency(String urgency) { + this.urgency = urgency; + } + + public String getInstructions() { + return instructions; + } + + public void setInstructions(String instructions) { + this.instructions = instructions; + } + + public String getOrderReason() { + return orderReason; + } + + public void setOrderReason(String orderReason) { + this.orderReason = orderReason; + } + + public String getDiscontinuedBy() { + return discontinuedBy; + } + + public void setDiscontinuedBy(String discontinuedBy) { + this.discontinuedBy = discontinuedBy; + } + + public DateTime getDiscontinuedDate() { + return discontinuedDate; + } + + public void setDiscontinuedDate(DateTime discontinuedDate) { + this.discontinuedDate = discontinuedDate; + } + + public String getDiscontinuedReason() { + return discontinuedReason; + } + + public void setDiscontinuedReason(String discontinuedReason) { + this.discontinuedReason = discontinuedReason; + } + + public String getFrequency() { + return frequency; + } + + public void setFrequency(String frequency) { + this.frequency = frequency; + } + + public String getBaseEntityId() { + return baseEntityId; + } + + public void setBaseEntityId(String baseEntityId) { + this.baseEntityId = baseEntityId; + } + + public String getOrderer() { + return orderer; + } + + public void setOrderer(String orderer) { + this.orderer = orderer; + } + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + public String getQuantityUnits() { + return quantityUnits; + } + + public void setQuantityUnits(String quantityUnits) { + this.quantityUnits = quantityUnits; + } + + public String getDosingType() { + return dosingType; + } + + public void setDosingType(String dosingType) { + this.dosingType = dosingType; + } + + public String getDose() { + return dose; + } + + public void setDose(String dose) { + this.dose = dose; + } + + public String getDescriptions() { + return descriptions; + } + + public void setDescriptions(String descriptions) { + this.descriptions = descriptions; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + +} diff --git a/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java b/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java index 8fd911dc9c..58d4927031 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/ErrorTrace.java @@ -1,6 +1,8 @@ package org.opensrp.domain; import java.util.Date; +import java.util.HashMap; +import java.util.Map; import org.codehaus.jackson.annotate.JsonProperty; import org.ektorp.support.TypeDiscriminator; @@ -10,7 +12,7 @@ /** * @author muhammad.ahmed@ihsinformatics.com Created on May 25, 2015 */ -@TypeDiscriminator("doc.type == 'Error'") +@TypeDiscriminator("doc.type == 'ErrorTrace'") public class ErrorTrace extends MotechBaseDataObject { /* @@ -37,7 +39,8 @@ public class ErrorTrace extends MotechBaseDataObject { private String documentType; @JsonProperty private String retryUrl; - + @JsonProperty + private Map details; // dateoccured , dateclosed , errortype =name, documenttype , submiturl public ErrorTrace() { @@ -48,9 +51,9 @@ public ErrorTrace() { * * */ - public ErrorTrace(DateTime dateOccurred, String errorType, String occuredAt, + public ErrorTrace(DateTime dateTime, String errorType, String occuredAt, String stackTrace, String status, String documentType) { - this.dateOccurred = dateOccurred; + this.dateOccurred = dateTime; // this.id=id; this.documentType = documentType; this.errorType = errorType; @@ -111,7 +114,21 @@ public void setRetryUrl(String retryUrl) { this.retryUrl = retryUrl; } + public Map getDetails() { + return details; + } + public void setDetails(Map details) { + this.details = details; + } + + public void addDetails(String key, String val) { + if(details == null){ + details = new HashMap<>(); + } + details.put(key, val); + } + public String getRecordId() { return recordId; @@ -130,8 +147,6 @@ public void setDate(DateTime date) { this.dateOccurred = date; } - - public String getOccurredAt() { return occurredAt; } diff --git a/opensrp-core/src/main/java/org/opensrp/domain/Multimedia.java b/opensrp-core/src/main/java/org/opensrp/domain/Multimedia.java index e8225ecb76..1e9a75de9b 100644 --- a/opensrp-core/src/main/java/org/opensrp/domain/Multimedia.java +++ b/opensrp-core/src/main/java/org/opensrp/domain/Multimedia.java @@ -1,15 +1,22 @@ package org.opensrp.domain; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; +import java.awt.Image; +import java.util.Date; +import java.util.Map; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; import org.codehaus.jackson.annotate.JsonProperty; import org.ektorp.support.TypeDiscriminator; +import org.joda.time.DateTime; import org.motechproject.model.MotechBaseDataObject; @TypeDiscriminator("doc.type == 'Multimedia'") -public class Multimedia extends MotechBaseDataObject { +public class Multimedia extends BaseDataObject { + @JsonProperty + private String fileName; @JsonProperty private String caseId; @JsonProperty @@ -20,20 +27,86 @@ public class Multimedia extends MotechBaseDataObject { private String filePath; @JsonProperty private String fileCategory; + @JsonProperty + private String extension; + @JsonProperty + private DateTime uploadDate; + @JsonProperty + private String description; + @JsonProperty + private String fileSize; + @JsonProperty + private Map comments; + public Multimedia(String caseId) { + this.caseId=caseId; + } public Multimedia() { - } - public Multimedia( String caseId, String providerId, String contentType, String filePath, String fileCategory) { + + public Multimedia(String caseId, String providerId, String contentType, String filePath, String fileCategory) + { this.caseId = caseId; this.providerId = providerId; this.contentType = contentType; this.filePath = filePath; this.fileCategory = fileCategory; + + } + public + Multimedia(String name, String caseId, String providerId, String contentType, String filePath, String fileCategory, String extension, + DateTime uploadDate, String description, String fileSize, Image previewImage, Map comments) { + this.caseId = caseId; + this.providerId = providerId; + this.contentType = contentType; + this.filePath = filePath; + this.fileCategory = fileCategory; + this.uploadDate=uploadDate; + this.description=description; + this.fileSize=fileSize; + this.comments=comments; + this.extension=extension; + } + public String getName() { + return fileName; } - public Multimedia withCaseId(String caseId) { + public void setName(String name) { + this.fileName = name; + } + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + public DateTime getUploadDate() { + return uploadDate; + } + public void setUploadDate(DateTime uploadDate) { + this.uploadDate = uploadDate; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getFileSize() { + return fileSize; + } + public void setFileSize(String fileSize) { + this.fileSize = fileSize; + } + public Map getComments() { + return comments; + } + public void setComments(Map comments) { + this.comments = comments; + } + public Multimedia withBaseEntityId(String caseId) { this.caseId = caseId; return this; } @@ -51,15 +124,47 @@ public Multimedia withFilePath(String filePath) { this.filePath = filePath; return this; } - + + public Multimedia withDescription(String description) { + this.description = description; + return this; + } public Multimedia withFileCategory(String fileCategory) { this.fileCategory = fileCategory; return this; } - public String getCaseId() { + public Multimedia withFileName(String name) { + this.fileName = name; + return this; + } + + public Multimedia withFileSize(String size) { + this.fileSize = size; + return this; + } + + public Multimedia withUploadDate(DateTime uploadDate) { + this.uploadDate = uploadDate; + return this; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getBaseEntityId() { return caseId; } + + public void setBaseEntityId(String baseEntityId) { + this.caseId = baseEntityId; + } + public String getProviderId() { return providerId; } @@ -72,10 +177,6 @@ public String getFilePath() { public String getFileCategory() { return fileCategory; } - - public void setCaseId(String caseId) { - this.caseId = caseId; - } public void setProviderId(String providerId) { this.providerId = providerId; } @@ -89,16 +190,6 @@ public void setFileCategory(String fileCategory) { this.fileCategory = fileCategory; } - @Override - public boolean equals(Object o) { - return EqualsBuilder.reflectionEquals(this, o, "id"); - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this, "id"); - } - @Override public String toString() { return ToStringBuilder.reflectionToString(this); diff --git a/opensrp-core/src/main/java/org/opensrp/domain/RelationShip.java b/opensrp-core/src/main/java/org/opensrp/domain/RelationShip.java new file mode 100644 index 0000000000..c3a47d3a41 --- /dev/null +++ b/opensrp-core/src/main/java/org/opensrp/domain/RelationShip.java @@ -0,0 +1,104 @@ +package org.opensrp.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonProperty; +import org.ektorp.support.TypeDiscriminator; +import org.joda.time.DateTime; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.codehaus.jackson.annotate.JsonIgnore; +import org.codehaus.jackson.annotate.JsonProperty; +import org.joda.time.DateTime; + +public class RelationShip { + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + public String getRelationship() { + return relationship; + } + + public void setRelationship(String relationship) { + this.relationship = relationship; + } + + @JsonProperty + private String relationship; + + @JsonProperty + private String person_b; + + public String getPerson_b() { + return person_b; + } + + public void setPerson_b(String person_b) { + this.person_b = person_b; + } + + @JsonProperty + private String startDate; + + @JsonProperty + private String endDate; + + public RelationShip() { + + } + + public RelationShip(String relationship,String person_b, String startDate,String endDate) + { + this.relationship=relationship; + this.person_b=person_b; + this.startDate=startDate; + this.endDate=endDate; + } + + /** + * WARNING: Overrides all existing obs + * @param obs + * @return + */ + + + @Override + public boolean equals(Object o) { + return EqualsBuilder.reflectionEquals(this, o, "; this.d", "revision"); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this, "id", "revision"); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllBaseEntities.java b/opensrp-core/src/main/java/org/opensrp/repository/AllBaseEntities.java deleted file mode 100644 index 7c2632e441..0000000000 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllBaseEntities.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.opensrp.repository; - -import java.util.List; - -import org.ektorp.ComplexKey; -import org.ektorp.CouchDbConnector; -import org.ektorp.support.GenerateView; -import org.ektorp.support.View; -import org.motechproject.dao.MotechBaseRepository; -import org.opensrp.common.AllConstants; -import org.opensrp.domain.BaseEntity; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Repository; - -@Repository -public class AllBaseEntities extends MotechBaseRepository { - - @Autowired - protected AllBaseEntities(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { - super(BaseEntity.class, db); - db.setRevisionLimit(revisionLimit); - } - - @GenerateView - public BaseEntity findByBaseEntityId(String baseEntityId) { - List entities = queryView("by_baseEntityId", baseEntityId); - if (entities == null || entities.isEmpty()) { - return null; - } - return entities.get(0); - } - - @View(name = "all_entities", map = "function(doc) { if (doc.baseEntityId && doc.identifiers) { emit(doc.id); } }") - public List findAllBaseEntities() { - return db.queryView(createQuery("all_entities").includeDocs(true), BaseEntity.class); - } - - @View(name = "all_entities_by_identifier", map = "function(doc) {if (doc.baseEntityId && doc.identifiers) {for(var key in doc.identifiers) {emit(doc.identifiers[key]);}}}") - public List findAllByIdentifier(String identifier) { - return db.queryView(createQuery("all_entities_by_identifier").key(identifier).includeDocs(true), BaseEntity.class); - } - - @View(name = "all_entities_by_identifier_of_type", map = "function(doc) {if (doc.baseEntityId && doc.identifiers) {for(var key in doc.identifiers) {emit([key, doc.identifiers[key]]);}}}") - public List findAllByIdentifier(String identifierType, String identifier) { - ComplexKey ckey = ComplexKey.of(identifierType, identifier); - return queryView("all_entities_by_identifier_of_type", ckey); - } -} diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllClients.java b/opensrp-core/src/main/java/org/opensrp/repository/AllClients.java index d78ea008a2..c55ce1f1f5 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllClients.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllClients.java @@ -25,7 +25,7 @@ public class AllClients extends MotechBaseRepository { @Autowired protected AllClients(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db, + @Qualifier(AllConstants.CLIENT_DATABASE_CONNECTOR) CouchDbConnector db, LuceneClientRepository lcr) { super(Client.class, db); this.lcr = lcr; @@ -52,12 +52,6 @@ public List findAllClients() { public List findAllByIdentifier(String identifier) { return db.queryView(createQuery("all_clients_by_identifier").key(identifier).includeDocs(true), Client.class); } - - @View(name = "all_clients_by_identifier_of_type", map = "function(doc) {if (doc.type === 'Client') {for(var key in doc.identifiers) {emit([key, doc.identifiers[key]]);}}}") - public List findAllByIdentifier(String identifierType, String identifier) { - ComplexKey ckey = ComplexKey.of(identifierType, identifier); - return db.queryView(createQuery("all_clients_by_identifier_of_type").key(ckey).includeDocs(true), Client.class); - } @View(name = "all_clients_by_attribute_of_type", map = "function(doc) {if (doc.type === 'Client') {for(var key in doc.attributes) {emit([key, doc.attributes[key]]);}}}") public List findAllByAttribute(String attributeType, String attribute) { @@ -65,11 +59,6 @@ public List findAllByAttribute(String attributeType, String attribute) { return db.queryView(createQuery("all_clients_by_attribute_of_type").key(ckey).includeDocs(true), Client.class); } - @View(name = "all_clients_by_matching_name", map = "function(doc) {if(doc.type === 'Client'){emit(doc.firstName, doc);emit(doc.lastName, doc);}}") - public List findAllByMatchingName(String nameMatches) { - return db.queryView(createQuery("all_clients_by_matching_name").startKey(nameMatches).endKey(nameMatches+"z").includeDocs(true), Client.class); - } - public List findByCriteria(String nameLike, String gender, DateTime birthdateFrom, DateTime birthdateTo, DateTime deathdateFrom, DateTime deathdateTo, String attributeType, String attributeValue, String addressType, String country, String stateProvince, String cityVillage, String countyDistrict, diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllDrugOrders.java b/opensrp-core/src/main/java/org/opensrp/repository/AllDrugOrders.java new file mode 100644 index 0000000000..5c82c96625 --- /dev/null +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllDrugOrders.java @@ -0,0 +1,89 @@ +package org.opensrp.repository; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + +import org.ektorp.CouchDbConnector; +import org.ektorp.support.GenerateView; +import org.ektorp.support.View; +import org.joda.time.DateTime; +import org.json.JSONException; +import org.json.JSONObject; +import org.motechproject.dao.MotechBaseRepository; +import org.opensrp.common.AllConstants; +import org.opensrp.domain.Drug; +import org.opensrp.domain.DrugOrder; +import org.opensrp.util.DateTimeTypeConverter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +@Repository +public class AllDrugOrders extends MotechBaseRepository { + @Autowired + protected AllDrugOrders(@Qualifier(AllConstants.DRUG_ORDER_DATABASE_CONNECTOR) CouchDbConnector db) { + super(DrugOrder.class, db); + } + + @GenerateView + public List findByBaseEntityId(String baseEntityId) { + return queryView("by_baseEntityId", baseEntityId); + } + + @GenerateView + public List findByOrderNumber(String orderNumber) { + return queryView("by_orderNumber", orderNumber); + } + + @View(name = "all_drugorders_by_drug", map = "function(doc) {if (doc.type === 'DrugOrder') {emit(doc.drug);}}") + public List findAllByDrug(String key) { + return db.queryView(createQuery("all_drugorders_by_drug").key(key).includeDocs(true), DrugOrder.class); + } + + @View(name = "all_drugorders_by_code", map = "function(doc) {if (doc.type === 'DrugOrder') {for(var key in doc.codes) {emit(doc.codes[key]);}}}") + public List findAllByCode(String code) { + return db.queryView(createQuery("all_drugorders_by_code").key(code).includeDocs(true), Drug.class); + } + + public DrugOrder merge(String drugOrderId, DrugOrder updatedOrder) + { + try{ + DrugOrder original = get(drugOrderId); + if(original == null){ + throw new IllegalArgumentException("No drug order found with given list of identifiers. Consider adding new!"); + } + + Gson gs = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).create(); + JSONObject originalJo = new JSONObject(gs.toJson(original)); + + JSONObject updatedJo = new JSONObject(gs.toJson(updatedOrder)); + List fn = Arrays.asList(DrugOrder.class.getDeclaredFields()); + + JSONObject mergedJson = new JSONObject(); + if (originalJo.length() > 0) { + mergedJson = new JSONObject(originalJo, JSONObject.getNames(originalJo)); + } + if (updatedJo.length() > 0) { + for (Field key : fn) { + String jokey = key.getName(); + if(updatedJo.has(jokey)) mergedJson.put(jokey, updatedJo.get(jokey)); + } + + original = gs.fromJson(mergedJson.toString(), DrugOrder.class); + + original.getCodes().putAll(updatedOrder.getCodes()); + } + + original.setDateEdited(DateTime.now()); + update(original); + return original; + } + catch(JSONException e){ + throw new RuntimeException(e); + } + } +} diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllDrugs.java b/opensrp-core/src/main/java/org/opensrp/repository/AllDrugs.java new file mode 100644 index 0000000000..1a64fc58ff --- /dev/null +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllDrugs.java @@ -0,0 +1,34 @@ +package org.opensrp.repository; + +import java.util.List; + +import org.ektorp.CouchDbConnector; +import org.ektorp.support.GenerateView; +import org.ektorp.support.View; +import org.motechproject.dao.MotechBaseRepository; +import org.opensrp.common.AllConstants; +import org.opensrp.domain.Drug; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; + +@Repository +public class AllDrugs extends MotechBaseRepository { + @Autowired + protected AllDrugs(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, + @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + super(Drug.class, db); + db.setRevisionLimit(revisionLimit); + } + + @View(name = "all_drugs_by_drugName", map = "function(doc) {if (doc.type === 'Drug') {emit(doc.drugName);}}") + public List findAllByName(String key) { + return db.queryView(createQuery("all_drugs_by_drugName").key(key).includeDocs(true), Drug.class); + } + + @View(name = "all_drugs_by_code", map = "function(doc) {if (doc.type === 'Drug') {for(var key in doc.codes) {emit(doc.codes[key]);}}}") + public List findAllByCode(String code) { + return db.queryView(createQuery("all_drugs_by_code").key(code).includeDocs(true), Drug.class); + } +} diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllErrorTrace.java b/opensrp-core/src/main/java/org/opensrp/repository/AllErrorTrace.java index 5ead474906..52f8c59f3d 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllErrorTrace.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllErrorTrace.java @@ -5,15 +5,18 @@ import org.ektorp.CouchDbConnector; import org.ektorp.DocumentNotFoundException; +import org.ektorp.support.GenerateView; import org.ektorp.support.View; import org.motechproject.dao.MotechBaseRepository; import org.opensrp.common.AllConstants; +import org.opensrp.domain.Client; import org.opensrp.domain.ErrorTrace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; +import com.mysql.jdbc.StringUtils; + /** * @author muhammad.ahmed@ihsinformatics.com * Created on May 25, 2015 @@ -23,47 +26,28 @@ public class AllErrorTrace extends MotechBaseRepository { @Autowired - protected AllErrorTrace(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, + protected AllErrorTrace( @Qualifier(AllConstants.OPENSRP_ERRORTRACE_DATABASE) CouchDbConnector db) { super(ErrorTrace.class, db); - db.setRevisionLimit(revisionLimit); } - //@GenerateView public ErrorTrace findById(String _id) throws DocumentNotFoundException{ - - /*db.queryView(createQuery("_id").keys(_id) - .includeDocs(true), ErrorTrace.class);*/ - ErrorTrace errors= (ErrorTrace)get(_id); - //List errors = queryView("_id", _id); - if (errors == null ) { - System.out.println("Error by id : = found nothing !"); - return null; - } - System.out.println("Error by id : = "+errors); - return errors; + return get(_id); } public boolean exists(String id) { return findById(id) != null; } - @View(name = "all_errors", map = "function(doc) { emit(doc.id); }") + @View(name = "all_errors", map = "function(doc) { if (doc.type === 'ErrorTrace') { emit(doc.id); } }") public List findAllErrors() throws DocumentNotFoundException{ return db.queryView(createQuery("all_errors").includeDocs(true), ErrorTrace.class); } - @View(name = "all_unsolved_errors", map = "function(doc) { if (doc.status === 'unsolved') { emit(doc.id); } }") - public List findAllUnSolvedErrors() throws DocumentNotFoundException { - return db.queryView(createQuery("all_unsolved_errors").includeDocs(true), - ErrorTrace.class); - } - - @View(name = "all_solved_errors", map = "function(doc) { if (doc.status === 'solved') { emit(doc.id); } }") - public List findAllSolvedErrors() throws DocumentNotFoundException { - return db.queryView(createQuery("all_solved__errors").includeDocs(true), - ErrorTrace.class); + @View(name = "all_errors_by_status", map = "function(doc) { if (doc.type === 'ErrorTrace') { emit(doc.status); } }") + public List findErrorsByStatus(String status) throws DocumentNotFoundException { + return db.queryView(createQuery("all_errors_by_status"). + key(status).includeDocs(true), ErrorTrace.class); } - } diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllEvents.java b/opensrp-core/src/main/java/org/opensrp/repository/AllEvents.java index 0f77e923ce..cc50baf91d 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllEvents.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllEvents.java @@ -23,7 +23,7 @@ public class AllEvents extends MotechBaseRepository{ @Autowired protected AllEvents(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db, + @Qualifier(AllConstants.EVENT_DATABASE_CONNECTOR) CouchDbConnector db, LuceneEventRepository ler) { super(Event.class, db); this.ler = ler; @@ -34,12 +34,6 @@ protected AllEvents(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") in public List findAllByIdentifier(String identifier) { return db.queryView(createQuery("all_events_by_identifier").key(identifier).includeDocs(true), Event.class); } - - @View(name = "all_events_by_identifier_of_type", map = "function(doc) {if (doc.type === 'Event') {for(var key in doc.identifiers) {emit([key, doc.identifiers[key]]);}}}") - public List findAllByIdentifier(String identifierType, String identifier) { - ComplexKey ckey = ComplexKey.of(identifierType, identifier); - return db.queryView(createQuery("all_events_by_identifier_of_type").key(ckey).includeDocs(true), Event.class); - } @GenerateView public List findByFormSubmissionId(String formSubmissionId) { diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllLocations.java b/opensrp-core/src/main/java/org/opensrp/repository/AllLocations.java index 7b8ce5a065..cad12e2db8 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllLocations.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllLocations.java @@ -18,7 +18,7 @@ public class AllLocations extends MotechBaseRepository { @Autowired protected AllLocations(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + @Qualifier(AllConstants.LOCATION_DATABASE_CONNECTOR) CouchDbConnector db) { super(Location.class, db); db.setRevisionLimit(revisionLimit); } diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllProviders.java b/opensrp-core/src/main/java/org/opensrp/repository/AllProviders.java index 49769655c4..6b1ef93ae9 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllProviders.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllProviders.java @@ -18,7 +18,7 @@ public class AllProviders extends MotechBaseRepository { @Autowired protected AllProviders(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + @Qualifier(AllConstants.PROVIDER_DATABASE_CONNECTOR) CouchDbConnector db) { super(Provider.class, db); db.setRevisionLimit(revisionLimit); } diff --git a/opensrp-core/src/main/java/org/opensrp/repository/AllUsers.java b/opensrp-core/src/main/java/org/opensrp/repository/AllUsers.java index 25bfc4b974..23a15749c6 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/AllUsers.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/AllUsers.java @@ -18,7 +18,7 @@ public class AllUsers extends MotechBaseRepository { @Autowired protected AllUsers(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + @Qualifier(AllConstants.PROVIDER_DATABASE_CONNECTOR) CouchDbConnector db) { super(User.class, db); db.setRevisionLimit(revisionLimit); } diff --git a/opensrp-core/src/main/java/org/opensrp/repository/MultimediaRepository.java b/opensrp-core/src/main/java/org/opensrp/repository/MultimediaRepository.java index a89e1ebf8e..378f160bca 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/MultimediaRepository.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/MultimediaRepository.java @@ -1,41 +1,73 @@ package org.opensrp.repository; +import java.util.Date; import java.util.List; import org.ektorp.CouchDbConnector; +import org.ektorp.Page; +import org.ektorp.PageRequest; +import org.ektorp.ViewQuery; import org.ektorp.support.GenerateView; import org.ektorp.support.View; +import org.joda.time.DateTime; import org.motechproject.dao.MotechBaseRepository; + import org.opensrp.common.AllConstants; import org.opensrp.domain.Multimedia; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; @Repository public class MultimediaRepository extends MotechBaseRepository { @Autowired - protected MultimediaRepository(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + protected MultimediaRepository( + @Qualifier(AllConstants.MULTIMEDIA_DATABASE_CONNECTOR) CouchDbConnector db) { super(Multimedia.class, db); - db.setRevisionLimit(revisionLimit); } @GenerateView - public Multimedia findByCaseId(String entityId) { - List files = queryView("by_caseId", entityId); + public Multimedia findByBaseEntityId(String baseEntityId) { + List files = queryView("by_baseEntityId", baseEntityId); if (files == null || files.isEmpty()) { return null; } return files.get(0); } - @View(name = "all_multimedia_files", map = "function(doc) { if (doc.type === 'Multimedia' && doc.providerId) { emit(doc.providerId, doc); } }") - public List all(String providerId) { - return db.queryView(createQuery("all_multimedia_files").key(providerId) - .includeDocs(true), Multimedia.class); + public List all(int pageSize) { + PageRequest pageRequest = PageRequest.firstPage(pageSize); + return db.queryForPage(createQuery("all").includeDocs(true), pageRequest, Multimedia.class).getRows(); + + } + + @View(name = "all_multimedia_by_ProviderId", map = "function(doc) {if (doc.type === 'Multimedia') {emit(doc.providerId);}}") + public List all(String providerId,int pageSize) { + PageRequest pageRequest = PageRequest.firstPage(pageSize); + return db.queryForPage(createQuery("all_multimedia_by_ProviderId").key(providerId).includeDocs(true), pageRequest, Multimedia.class).getRows(); + } + + @View(name = "all_multimedia_by_contentType", map = "function(doc) {if (doc.type === 'Multimedia') {emit(doc.contentType);}}") + public List allByContent(int pageSize,String content) { + PageRequest pageRequest = PageRequest.firstPage(pageSize); + return db.queryForPage(createQuery("all_multimedia_by_contentType").key(content).includeDocs(true), pageRequest, Multimedia.class).getRows(); + } + @View(name = "all_multimedia_by_fileName", map = "function(doc) {if (doc.type === 'Multimedia') {emit(doc.fileName);}}") + public List allByName(int pageSize,String name) { + PageRequest pageRequest = PageRequest.firstPage(pageSize); + return db.queryForPage(createQuery("all_multimedia_by_fileName").key(name).includeDocs(true), pageRequest, Multimedia.class).getRows(); +} + + @View(name = "all_multimedia_by_Date", map = "function(doc) {if (doc.type === 'Multimedia') {emit(doc.uploadDate);}}") + public List allByDate(int pageSize,DateTime startTime,DateTime endTime) { + PageRequest pageRequest = PageRequest.firstPage(pageSize); + return db.queryForPage(createQuery("all_multimedia_by_Date").startKey(startTime).endKey(endTime).includeDocs(true), + pageRequest, Multimedia.class).getRows(); + + } } diff --git a/opensrp-core/src/main/java/org/opensrp/repository/lucene/LuceneClientRepository.java b/opensrp-core/src/main/java/org/opensrp/repository/lucene/LuceneClientRepository.java index e63ea8483c..4785a347a2 100644 --- a/opensrp-core/src/main/java/org/opensrp/repository/lucene/LuceneClientRepository.java +++ b/opensrp-core/src/main/java/org/opensrp/repository/lucene/LuceneClientRepository.java @@ -18,9 +18,13 @@ import java.io.IOException; import java.util.List; +import org.ektorp.CouchDbConnector; +import org.ektorp.impl.StdCouchDbInstance; import org.joda.time.DateTime; +import org.opensrp.common.AllConstants; import org.opensrp.domain.Client; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.github.ldriscoll.ektorplucene.CouchDbRepositorySupportWithLucene; @@ -41,9 +45,10 @@ public class LuceneClientRepository extends CouchDbRepositorySupportWithLucene { @Autowired protected AllActions(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + @Qualifier(AllConstants.ACTION_DATABASE_CONNECTOR) CouchDbConnector db) { super(Action.class, db); db.setRevisionLimit(revisionLimit); } diff --git a/opensrp-core/src/main/java/org/opensrp/scheduler/repository/AllAlerts.java b/opensrp-core/src/main/java/org/opensrp/scheduler/repository/AllAlerts.java index 863d5d7b60..60b95d14a2 100644 --- a/opensrp-core/src/main/java/org/opensrp/scheduler/repository/AllAlerts.java +++ b/opensrp-core/src/main/java/org/opensrp/scheduler/repository/AllAlerts.java @@ -31,7 +31,7 @@ public class AllAlerts extends MotechBaseRepository { @Autowired protected AllAlerts(@Value("#{opensrp['couchdb.opensrp-db.revision-limit']}") int revisionLimit, - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) CouchDbConnector db) { + @Qualifier(AllConstants.ALERT_DATABASE_CONNECTOR) CouchDbConnector db) { super(Alert.class, db); db.setRevisionLimit(revisionLimit); } @@ -50,16 +50,6 @@ public List findActiveByProviderAndTimestamp(String provider, long timeSt return db.queryView(createQuery("alert_by_provider_and_time_active").startKey(startKey).endKey(endKey).includeDocs(true), Alert.class); } - @View(name = "alert_by_provider_entityId_trigger", - map = "function(doc) { " + - "if(doc.type === 'Alert') {" + - "emit([doc.providerId, doc.entityId, doc.triggerName], null)} " + - "}") - public List findAlertByProviderEntityIdTriggerName(String provider, String entityId, String triggerName) { - ComplexKey key = ComplexKey.of(provider, entityId, triggerName); - return db.queryView(createQuery("alert_by_provider_entityId_trigger").key(key).includeDocs(true), Alert.class); - } - @View(name = "alert_by_provider_entityId_trigger_active", map = "function(doc) { " + "if(doc.type === 'Alert' && doc.isActive) {" + diff --git a/opensrp-core/src/main/java/org/opensrp/scheduler/service/ActionService.java b/opensrp-core/src/main/java/org/opensrp/scheduler/service/ActionService.java index f0a92635c7..aa357783f2 100644 --- a/opensrp-core/src/main/java/org/opensrp/scheduler/service/ActionService.java +++ b/opensrp-core/src/main/java/org/opensrp/scheduler/service/ActionService.java @@ -41,10 +41,6 @@ public List getAlertsActiveForProvider(String providerId, long timeStamp) public List findByCaseIdScheduleAndTimeStamp(String caseId, String schedule, DateTime start, DateTime end) { return allActions.findByCaseIdScheduleAndTimeStamp(caseId, schedule, start, end); } - - public List findAlertByEntityIdScheduleAndTimeStamp(String entityId, String schedule, DateTime start, DateTime end) { - return allAlerts.findByEntityIdTriggerAndTimeStamp(entityId, schedule, start, end); - } public void alertForBeneficiary(String beneficiaryType, String caseID, String anmIdentifier, String scheduleName, String visitCode, AlertStatus alertStatus, DateTime startDate, DateTime expiryDate) { allActions.addOrUpdateAlert(new Action(caseID, anmIdentifier, ActionData.createAlert(beneficiaryType, scheduleName, visitCode, alertStatus, startDate, expiryDate))); diff --git a/opensrp-core/src/main/java/org/opensrp/service/BaseEntityService.java b/opensrp-core/src/main/java/org/opensrp/service/BaseEntityService.java deleted file mode 100644 index 1b4c0b5e44..0000000000 --- a/opensrp-core/src/main/java/org/opensrp/service/BaseEntityService.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.opensrp.service; - -import java.util.List; - -import org.opensrp.domain.BaseEntity; -import org.opensrp.repository.AllBaseEntities; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class BaseEntityService { - - private final AllBaseEntities allBaseEntities; - - @Autowired - public BaseEntityService(AllBaseEntities allBaseEntities ) { - this.allBaseEntities = allBaseEntities; - } - - public List getAllBaseEntities() { - return allBaseEntities.findAllBaseEntities(); - } - - public BaseEntity findByBaseEntityId(String baseEntityId) { - return allBaseEntities.findByBaseEntityId(baseEntityId); - } - - public List findByIdentifier(String identifier) { - return allBaseEntities.findAllByIdentifier(identifier); - } - - public List findByIdentifier(String identifierType, - String identifier) { - return allBaseEntities.findAllByIdentifier(identifierType, identifier); - } -} diff --git a/opensrp-core/src/main/java/org/opensrp/service/ClientService.java b/opensrp-core/src/main/java/org/opensrp/service/ClientService.java index d974e97ce7..11e43afbf1 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/ClientService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/ClientService.java @@ -10,6 +10,7 @@ import org.json.JSONObject; import org.opensrp.domain.Address; import org.opensrp.domain.Client; +import org.opensrp.domain.RelationShip; import org.opensrp.repository.AllClients; import org.opensrp.util.DateTimeTypeConverter; import org.springframework.beans.factory.annotation.Autowired; @@ -41,19 +42,11 @@ public List findAllClients() { public List findAllByIdentifier(String identifier) { return allClients.findAllByIdentifier(identifier); } - - public List findAllByIdentifier(String identifierType, String identifier) { - return allClients.findAllByIdentifier(identifierType, identifier); - } public List findAllByAttribute(String attributeType, String attribute) { return allClients.findAllByAttribute(attributeType, attribute); } - public List findAllByMatchingName(String nameMatches) { - return allClients.findAllByMatchingName(nameMatches); - } - public List findByCriteria(String nameLike, String gender, DateTime birthdateFrom, DateTime birthdateTo, DateTime deathdateFrom, DateTime deathdateTo, String attributeType, String attributeValue, String addressType, String country, String stateProvince, String cityVillage, String countyDistrict, @@ -186,6 +179,10 @@ public Client mergeClient(Client updatedClient) for (String k : updatedClient.getAttributes().keySet()) { original.addAttribute(k, updatedClient.getAttribute(k)); } + + for (RelationShip r : updatedClient.getRelationships()) { + original.addRelationship(r); + } } original.setDateEdited(DateTime.now()); diff --git a/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java b/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java index 9ddc1f6921..78441611b0 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/ErrorTraceService.java @@ -21,7 +21,6 @@ public class ErrorTraceService { private final AllErrorTrace allErrorTrace; - @Autowired public ErrorTraceService(AllErrorTrace allErrorTrace) { this.allErrorTrace=allErrorTrace; @@ -51,63 +50,21 @@ public void log(String errorType , String documentType, String recordId ,String error.setRetryUrl(retryURL); error.setDateOccurred(DateTime.now()); addError(error); - } public void updateError(ErrorTrace entity){ allErrorTrace.update(entity); } - public List getAllErrors() throws DocumentNotFoundException{ - - - ArrayList allErrorList= (ArrayList) allErrorTrace.findAllErrors(); - if(null==allErrorList || allErrorList.isEmpty()){ - return null; - - } - - - return allErrorList; - + public List getAllError() throws DocumentNotFoundException{ + return allErrorTrace.findAllErrors(); } - public List getAllSolvedErrors() throws DocumentNotFoundException{ - - - ArrayList allErrorList= (ArrayList) allErrorTrace.findAllSolvedErrors(); - if(null==allErrorList || allErrorList.isEmpty()){ - return null; - - } - - - return allErrorList; - + public List getErrorsByStatus(String errorStatus) throws DocumentNotFoundException{ + return allErrorTrace.findErrorsByStatus(errorStatus); } - - public List getAllUnsolvedErrors() throws DocumentNotFoundException{ - - ArrayList allErrorList= (ArrayList) allErrorTrace.findAllUnSolvedErrors(); - if(null==allErrorList || allErrorList.isEmpty()){ - return null; - - } - - - return allErrorList; - - } - public ErrorTrace getError(String id) throws DocumentNotFoundException{ - - return allErrorTrace.findById(id); - - + return allErrorTrace.findById(id); } - - - - } diff --git a/opensrp-core/src/main/java/org/opensrp/service/EventService.java b/opensrp-core/src/main/java/org/opensrp/service/EventService.java index 4a54505832..01cf7324e2 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/EventService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/EventService.java @@ -31,10 +31,6 @@ public EventService(AllEvents allEvents) public List findAllByIdentifier(String identifier) { return allEvents.findAllByIdentifier(identifier); } - - public List findAllByIdentifier(String identifierType, String identifier) { - return allEvents.findAllByIdentifier(identifierType, identifier); - } public Event getByBaseEntityAndFormSubmissionId(String baseEntityId, String formSubmissionId) { diff --git a/opensrp-core/src/main/java/org/opensrp/service/MultimediaService.java b/opensrp-core/src/main/java/org/opensrp/service/MultimediaService.java index 7376cd3568..a54d279f6a 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/MultimediaService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/MultimediaService.java @@ -1,10 +1,15 @@ package org.opensrp.service; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; import java.util.List; +import org.apache.commons.io.FilenameUtils; +import org.joda.time.DateTime; +import org.json.JSONException; import org.opensrp.domain.Multimedia; -import org.opensrp.dto.form.MultimediaDTO; import org.opensrp.repository.MultimediaRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -21,25 +26,30 @@ public class MultimediaService { public MultimediaService(MultimediaRepository multimediaRepository, @Value("#{opensrp['multimedia.directory.name']}") String baseMultimediaDirPath) { this.multimediaRepository = multimediaRepository; } - - public String saveMultimediaFile(MultimediaDTO multimediaDTO, MultipartFile file) { + + public String saveMultimediaFile(Multimedia multimedia, MultipartFile file) { - boolean uploadStatus = uploadFile(multimediaDTO, file); + boolean uploadStatus = uploadFile(multimedia, file); if (uploadStatus) { try { Multimedia multimediaFile = new Multimedia() - .withCaseId(multimediaDTO.caseId()) - .withProviderId(multimediaDTO.providerId()) - .withContentType(multimediaDTO.contentType()) + .withBaseEntityId(multimedia.getBaseEntityId()) + .withProviderId(multimedia.getProviderId()) + .withContentType(multimedia.getContentType()) .withFilePath(multimediaDirPath) - .withFileCategory(multimediaDTO.fileCategory()); - + .withFileCategory(multimedia.getFileCategory()) + .withFileName(multimedia.getName()) + .withFileSize(multimedia.getFileSize()) + .withUploadDate(multimedia.getUploadDate()) + .withDescription(multimedia.getDescription()); + multimediaRepository.add(multimediaFile); return "success"; } catch (Exception e) { + System.out.println(e.getMessage()); e.getMessage(); } } @@ -48,63 +58,70 @@ public String saveMultimediaFile(MultimediaDTO multimediaDTO, MultipartFile file } - public boolean uploadFile(MultimediaDTO multimediaDTO, + public List getMultimediaData(int pageSize) throws JSONException + { + List data=multimediaRepository.all(pageSize); + return data; + } + + public List getMultimediaFiles(String providerId) { + return multimediaRepository.all(providerId,50); + } + + public List getMultimediaDataByName(int pageSize, String searchByName) throws JSONException + { + List data=multimediaRepository.allByName(pageSize,searchByName); + return data; + } + + public List getMultimediaDataByContent(int pageSize, String searchByContent ) throws JSONException + { + List data=multimediaRepository.allByContent(pageSize,searchByContent); + return data; + } + + public List getMultimediaDataByDate(int pageSize, DateTime startDate,DateTime endDate ) throws JSONException + { + List data=multimediaRepository.allByDate(pageSize,startDate,endDate); + return data; + } + + public boolean uploadFile(Multimedia multimedia, MultipartFile multimediaFile) { - String baseMultimediaDirPath = "../assets/multimedia"; - // String baseMultimediaDirPath = System.getProperty("user.home"); - if (!multimediaFile.isEmpty()) { try { - multimediaDirPath = baseMultimediaDirPath - + File.separator + multimediaDTO.providerId() - + File.separator; - - switch (multimediaDTO.contentType()) { + File multimediaDir; + switch (multimedia.getContentType()) { - case "application/octet-stream": - multimediaDirPath += "videos" + File.separator - + multimediaDTO.caseId() + ".mp4"; - break; - - case "image/jpeg": - multimediaDirPath += "images" + File.separator - + multimediaDTO.caseId() + ".jpg"; + case "video": + multimediaDirPath = "videos" + File.separator + + multimedia.getBaseEntityId() +"."+ multimedia.getExtension(); break; - - case "image/gif": - multimediaDirPath += "images" + File.separator - + multimediaDTO.caseId() + ".gif"; + case "document": + multimediaDirPath = "documents" + File.separator + + multimedia.getBaseEntityId() +"."+ multimedia.getExtension(); break; - - case "image/png": - multimediaDirPath += "images" + File.separator - + multimediaDTO.caseId() + ".png"; + case "image": + multimediaDirPath = "images" + File.separator + + multimedia.getBaseEntityId() +"."+ multimedia.getExtension(); break; - default: - multimediaDirPath += "images" + File.separator - + multimediaDTO.caseId() + ".jpg"; + multimediaDirPath = "documents" + File.separator + + multimedia.getBaseEntityId() +"."+ multimedia.getExtension(); break; - } - - File multimediaDir = new File(multimediaDirPath); - - multimediaFile.transferTo(multimediaDir); - - /* - byte[] bytes = multimediaFile.getBytes(); - - BufferedOutputStream stream = new BufferedOutputStream( - new FileOutputStream(multimediaDirPath)); - stream.write(bytes); - stream.close();*/ - + + multimediaDir = new File(multimediaDirPath); + if(!multimediaDir.getParentFile().exists()) { + multimediaDir.getParentFile().mkdirs(); + } + multimediaFile.transferTo(multimediaDir); return true; } catch (Exception e) { + e.printStackTrace(); return false; } } else { @@ -112,7 +129,4 @@ public boolean uploadFile(MultimediaDTO multimediaDTO, } } - public List getMultimediaFiles(String providerId) { - return multimediaRepository.all(providerId); - } } diff --git a/opensrp-core/src/main/java/org/opensrp/service/XlsFormDownloaderService.java b/opensrp-core/src/main/java/org/opensrp/service/XlsFormDownloaderService.java index 0d0a805259..f3260ab5aa 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/XlsFormDownloaderService.java +++ b/opensrp-core/src/main/java/org/opensrp/service/XlsFormDownloaderService.java @@ -12,7 +12,6 @@ import javax.xml.parsers.ParserConfigurationException; import org.codehaus.jackson.JsonProcessingException; -import org.joda.time.DateTime; import org.opensrp.util.FileCreator; import org.opensrp.util.JsonParser; import org.opensrp.util.NetClientGet; @@ -24,8 +23,8 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import com.sun.org.apache.xml.internal.serialize.OutputFormat; -import com.sun.org.apache.xml.internal.serialize.XMLSerializer; +// import com.sun.org.apache.xml.internal.serialize.OutputFormat; +// import com.sun.org.apache.xml.internal.serialize.XMLSerializer; /** @@ -133,7 +132,8 @@ public String formatXML(String input) } public String format(String unformattedXml) { - try { + return unformattedXml; + /*try { final org.w3c.dom.Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); @@ -147,7 +147,7 @@ public String format(String unformattedXml) { return out.toString(); } catch (IOException e) { throw new RuntimeException(e); - } + }*/ } private org.w3c.dom.Document parseXmlFile(String in) { diff --git a/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormEntityConverter.java b/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormEntityConverter.java index 59c45d76de..a6a0868cb0 100644 --- a/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormEntityConverter.java +++ b/opensrp-core/src/main/java/org/opensrp/service/formSubmission/FormEntityConverter.java @@ -4,8 +4,6 @@ import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -24,6 +22,7 @@ import org.opensrp.domain.Client; import org.opensrp.domain.Event; import org.opensrp.domain.Obs; +import org.opensrp.domain.RelationShip; import org.opensrp.form.domain.FormSubmission; import org.opensrp.form.service.FormAttributeParser; import org.opensrp.form.service.FormFieldMap; @@ -135,6 +134,7 @@ private Event getEventForSubform(FormSubmissionMap fs, String eventType, Subform return createEvent(subformInstance.entityId(), subformInstance.formAttributes().get("openmrs_entity_id"), subformInstance.fields(), fs); } + /** * Get field name for specified openmrs entity in given form submission * @param en @@ -157,9 +157,11 @@ String getFieldName(FormEntity en, SubformMap subf) { } String getFieldName(FormEntity en, List fields) { + for (FormFieldMap f : fields) { if(f.fieldAttributes().containsKey("openmrs_entity") && - f.fieldAttributes().get("openmrs_entity").equalsIgnoreCase(en.entity()) + (f.fieldAttributes().get("openmrs_entity").equalsIgnoreCase(en.entity()) || + f.fieldAttributes().get("openmrs_entity").equalsIgnoreCase("person_relationship")) && f.fieldAttributes().get("openmrs_entity_id").equalsIgnoreCase(en.entityId())){ return f.name(); } @@ -202,6 +204,15 @@ Map extractAddresses(FormSubmissionMap fs) throws ParseExceptio return paddr; } + Map extractRelation(FormSubmissionMap fs) throws ParseException { + Map paddr = new HashMap<>(); + for (FormFieldMap fl : fs.fields()) { + fillRelationShipFields(fl, paddr); + + } + return paddr; + } + Map extractAddressesForSubform(SubformMap subf) throws ParseException { Map paddr = new HashMap<>(); for (FormFieldMap fl : subf.fields()) { @@ -210,6 +221,15 @@ Map extractAddressesForSubform(SubformMap subf) throws ParseExc return paddr; } + void fillRelationShipFields(FormFieldMap fl, Map relatShip) throws ParseException { + Map att = fl.fieldAttributes(); + if(att.containsKey("openmrs_entity") && att.get("openmrs_entity").equalsIgnoreCase("person_relationship")){ + String relationShipType = att.get("openmrs_entity_id"); + String person_b= fl.value(); + relatShip.put(relationShipType,new RelationShip(relationShipType, person_b, "", "")); + } + } + void fillAddressFields(FormFieldMap fl, Map addresses) throws ParseException { Map att = fl.fieldAttributes(); if(att.containsKey("openmrs_entity") && att.get("openmrs_entity").equalsIgnoreCase("person_address")){ @@ -364,6 +384,7 @@ public Client createBaseClient(FormSubmissionMap fs) throws ParseException { } birthdateApprox = bde > 0 ? true:false; } + ArrayList relationShips = new ArrayList<>(extractRelation(fs).values()); String aproxdd = fs.getFieldValue(getFieldName(Person.deathdate_estimated, fs)); Boolean deathdateApprox = false; if(!StringUtils.isEmptyOrWhitespaceOnly(aproxdd) && NumberUtils.isNumber(aproxdd)){ @@ -385,7 +406,7 @@ public Client createBaseClient(FormSubmissionMap fs) throws ParseException { .withLastName(lastName) .withBirthdate(birthdate, birthdateApprox) .withDeathdate(deathdate, deathdateApprox) - .withGender(gender); + .withGender(gender).withRelation(relationShips); c.withAddresses(addresses) .withAttributes(extractAttributes(fs)) diff --git a/opensrp-core/src/main/resources/applicationContext-opensrp.xml b/opensrp-core/src/main/resources/applicationContext-opensrp.xml index 436d422290..d851c9f2d4 100644 --- a/opensrp-core/src/main/resources/applicationContext-opensrp.xml +++ b/opensrp-core/src/main/resources/applicationContext-opensrp.xml @@ -29,15 +29,45 @@ - - - + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + diff --git a/opensrp-core/src/test/java/org/opensrp/MultimediaServiceTest.java b/opensrp-core/src/test/java/org/opensrp/MultimediaServiceTest.java deleted file mode 100644 index 9cff28bf3b..0000000000 --- a/opensrp-core/src/test/java/org/opensrp/MultimediaServiceTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.opensrp; - -import static org.mockito.MockitoAnnotations.initMocks; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.opensrp.domain.Multimedia; -import org.opensrp.dto.form.MultimediaDTO; -import org.opensrp.repository.MultimediaRepository; -import org.opensrp.service.MultimediaService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.multipart.MultipartFile; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") -public class MultimediaServiceTest { - - @Mock - private MultimediaService multimediaService; - - @Autowired - private MultimediaRepository multimediaRepository; - - @Autowired - @Value("#{opensrp['multimedia.directory.name']}") - private String multimediaDirPath; - - @Before - public void setUp() throws Exception - { - initMocks(this); - multimediaService = new MultimediaService(multimediaRepository, multimediaDirPath); - } - - @Ignore @Test - public void shouldSaveMultimediaFile() throws FileNotFoundException - { - MultimediaDTO multimedia = new MultimediaDTO("1234567891", "opensrp","image/jpeg", "../assets/multimedia/opensrp/images/1234567891.jpg","nid"); - - FileInputStream fis = new FileInputStream("/home/julkar/nain/image.jpeg"); - - MultipartFile multipartFile = null; - - try { - multipartFile = new MockMultipartFile("file", fis); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - String status = multimediaService.saveMultimediaFile(multimedia,multipartFile); - - Assert.assertEquals("success", status); - - } - @Ignore @Test - public void shouldGetMultimediaFiles() throws FileNotFoundException - { - MultimediaDTO multimediaDTO = new MultimediaDTO("1234567890", "opensrp","image/jpeg", "../assets/multimedia/opensrp/images/1234567890.jpg","profile"); - - Multimedia expectedMultimedia = new Multimedia() - .withCaseId(multimediaDTO.caseId()) - .withProviderId(multimediaDTO.providerId()) - .withContentType(multimediaDTO.contentType()) - .withFilePath(multimediaDTO.filePath()) - .withFileCategory(multimediaDTO.fileCategory()); - - FileInputStream fis = new FileInputStream("/home/julkar/nain/image.jpeg"); - - MultipartFile multipartFile = null; - - try { - multipartFile = new MockMultipartFile("file", fis); - } catch (IOException e) { - e.printStackTrace(); - } - - boolean status = multimediaService.uploadFile(multimediaDTO, multipartFile); - - if(status) - multimediaRepository.add(expectedMultimedia); - - List multimediaFiles = multimediaService.getMultimediaFiles("opensrp"); - - for(Multimedia actualMultimedia : multimediaFiles) - { - if(actualMultimedia.getCaseId().equals(multimediaDTO.caseId())) - Assert.assertEquals(expectedMultimedia.getFilePath(),actualMultimedia.getFilePath()); - } - } -} diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllActionsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllActionsIntegrationTest.java index b4567a70b2..3ff9ef5c42 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllActionsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllActionsIntegrationTest.java @@ -22,7 +22,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllActionsIntegrationTest { @Autowired AllActions allActions; diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllAlertsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllAlertsIntegrationTest.java index ae61e0d1c8..f54c45106e 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllAlertsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllAlertsIntegrationTest.java @@ -27,7 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllAlertsIntegrationTest { @Autowired AllAlerts allAlerts; diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java deleted file mode 100644 index 8ffff25d67..0000000000 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllBaseEntitiesIntegrationTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.opensrp.repository.it; - -import static org.mockito.MockitoAnnotations.initMocks; -import static org.junit.Assert.*; - -import java.util.Date; -import java.util.List; - -import org.ektorp.CouchDbConnector; -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opensrp.common.AllConstants; -import org.opensrp.common.Gender; -import org.opensrp.domain.Address; -import org.opensrp.domain.BaseEntity; -import org.opensrp.domain.Client; -import org.opensrp.repository.AllBaseEntities; -import org.opensrp.repository.AllClients; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") -public class AllBaseEntitiesIntegrationTest { - - @Autowired - @Qualifier(AllConstants.OPENSRP_DATABASE_CONNECTOR) - CouchDbConnector db; - - @Autowired - private AllBaseEntities allBaseEntities; - @Autowired - private AllClients allClients; - - @Before - public void setUp() throws Exception { - allClients.removeAll(); - initMocks(this); - } - - @Test - public void shouldFetchBaseEntityForClientData() throws Exception { - String baseEntityId = "testclient1"; - Client c = new Client(baseEntityId) - .withBirthdate(new DateTime(), false) - .withFirstName("C first n") - .withLastName("C last n") - .withMiddleName("C middle n") - .withGender(Gender.FEMALE); - c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); - c.withAttribute("ETHNICITY", "Mughal"); - c.withIdentifier("Program ID", "01001221"); - - allClients.add(c); - - BaseEntity be = allBaseEntities.findByBaseEntityId("testclient1"); - assertEquals("testclient1", be.getBaseEntityId()); - assertTrue(Client.class.getSimpleName().equals(be.type())); - assertEquals("birthplace", be.getAddresses().get(0).getAddressType()); - assertEquals("Mughal", be.getAttribute("ethnicity")); - assertEquals("01001221", be.getIdentifier("program id")); - - List be2 = allBaseEntities.findAllByIdentifier("01001221"); - assertTrue(be2.size() == 1); - assertEquals("testclient1", be2.get(0).getBaseEntityId()); - - List be3 = allBaseEntities.findAllByIdentifier("Program ID", "01001221"); - assertTrue(be3.size() == 1); - assertEquals("testclient1", be3.get(0).getBaseEntityId()); - } - - @Test - public void shouldFetchBaseEntityByIdentifier() throws Exception { - String baseEntityId = "testclient2"; - Client c = new Client(baseEntityId) - .withBirthdate(new DateTime(), false) - .withFirstName("C first n") - .withLastName("C last n") - .withMiddleName("C middle n") - .withGender(Gender.MALE); - c.withAddress(new Address("birthplace", new DateTime(System.currentTimeMillis()-1000*60*60*24*2), DateTime.now(), null, "lat", "lon", "75210", "Sindh", "Pakistan")); - c.withAttribute("ETHNICITY", "Mughal"); - c.withIdentifier("Program ID", "01001222"); - - allClients.add(c); - - BaseEntity be = allBaseEntities.findByBaseEntityId("testclient2"); - assertEquals("testclient2", be.getBaseEntityId()); - assertTrue(Client.class.getSimpleName().equals(be.type())); - assertEquals("01001222", be.getIdentifier("program id")); - - List be2 = allBaseEntities.findAllByIdentifier("01001222"); - assertTrue(be2.size() == 1); - assertEquals("testclient2", be2.get(0).getBaseEntityId()); - - List be3 = allBaseEntities.findAllByIdentifier("Program ID", "01001222"); - assertTrue(be3.size() == 1); - assertEquals("testclient2", be3.get(0).getBaseEntityId()); - } - -} diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java index dedd7b9007..a4349cc95d 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllClientsIntegrationTest.java @@ -47,7 +47,7 @@ import com.google.gson.GsonBuilder; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllClientsIntegrationTest { //TODO detailed testign @@ -227,7 +227,7 @@ public void shouldFetchClientByIdentifier() assertTrue(ce2.size() == 1); assertEquals("testclient2", ce2.get(0).getBaseEntityId()); - List ce3 = clientService.findAllByIdentifier("Program ID", "01001222"); + List ce3 = clientService.findAllByIdentifier("01001222"); assertTrue(ce3.size() == 1); assertEquals("testclient2", ce3.get(0).getBaseEntityId()); } diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java index 75641379dc..619fadf284 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllErrorTraceIntegrationTest.java @@ -1,8 +1,10 @@ package org.opensrp.repository.it; import static org.mockito.MockitoAnnotations.initMocks; +import static org.junit.Assert.*; import java.util.Date; +import java.util.Random; import org.joda.time.DateTime; import org.junit.Before; @@ -16,29 +18,44 @@ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllErrorTraceIntegrationTest { @Autowired private AllErrorTrace allErrorTrace; + @Before public void setUp() throws Exception { initMocks(this); + allErrorTrace.removeAll(); } @Test public void shouldAddError()throws Exception { //ErrorTrace error=new ErrorTrace(new Date(), "Error Testing" , "not availalbe","this is an Testing Error", "unsolved"); + Random ran=new Random(); + try + { + throw new RuntimeException("My Test Msg"); + } + catch(Exception e){ + for(int i=0;i<15;i++) + { ErrorTrace error=new ErrorTrace(); error.setErrorType("error loggging test"); error.setDate(DateTime.now()); error.setStackTrace("Complete Stack Trace :"); error.setStatus("unsolved"); error.setDocumentType("Test Document"); - // error.setErrorType("test Error"); + error.setRecordId(String.valueOf(ran.nextInt(100000)+ran.nextInt(1002))); allErrorTrace.add(error); + } + assertTrue(allErrorTrace.findErrorsByStatus("unsolved").size() == 15); + assertTrue(allErrorTrace.findErrorsByStatus("solved").size() <15); + + } } diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllEventsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllEventsIntegrationTest.java index ff0dfa4153..814fe3b320 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllEventsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllEventsIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllEventsIntegrationTest { //TODO Detailed testing @Autowired diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java index 267a9f0f94..528ff1223b 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllLocationsIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllLocationsIntegrationTest { diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllOrderTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllOrderTest.java new file mode 100644 index 0000000000..08a3322790 --- /dev/null +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllOrderTest.java @@ -0,0 +1,43 @@ +package org.opensrp.repository.it; + +import static java.util.Arrays.asList; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.opensrp.dto.AlertStatus.normal; +import static org.opensrp.dto.BeneficiaryType.mother; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensrp.domain.Drug; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.opensrp.repository.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-opensrp.xml") +public class AllOrderTest { + @Autowired + AllDrugs allDrugs; + + @Before + public void setUp() throws Exception { + allDrugs.removeAll(); + } + + @Test + public void shouldSaveADrug() throws Exception { + Drug Drugs = new Drug("525d1ccc-2f5c-49ec-b5f6-eea2206c0c5d"); + allDrugs.add(Drugs); + + List allTheDrugInDB = allDrugs.getAll(); + assertEquals(1, allTheDrugInDB.size()); + assertEquals(Drugs, allTheDrugInDB.get(0)); + } + +} diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllProvidersIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllProvidersIntegrationTest.java index 725396ac4f..6853585979 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllProvidersIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllProvidersIntegrationTest.java @@ -17,7 +17,7 @@ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllProvidersIntegrationTest { @Autowired diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/AllUsersIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/AllUsersIntegrationTest.java index 476d34bd22..c6b72752fa 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/AllUsersIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/AllUsersIntegrationTest.java @@ -8,23 +8,19 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.opensrp.domain.BaseEntity; import org.opensrp.domain.User; -import org.opensrp.repository.AllBaseEntities; import org.opensrp.repository.AllUsers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class AllUsersIntegrationTest { @Autowired private AllUsers allUsers; - @Autowired - private AllBaseEntities allBaseEntities; @Before public void setUp() throws Exception { @@ -41,8 +37,6 @@ public void shouldAddUser()throws Exception List roles = new ArrayList<>(); roles.add("tlp"); - - BaseEntity baseEntity = allBaseEntities.findByBaseEntityId("0001"); User domainUser = new User("0001") .withUsername("FWA2") diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/ConfigServiceIntegrationTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/ConfigServiceIntegrationTest.java index 9c11b10174..57a07aaa88 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/ConfigServiceIntegrationTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/ConfigServiceIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ConfigServiceIntegrationTest { diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/FormLifeCycleTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/FormLifeCycleTest.java index 3f33c02310..160aa17eaf 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/FormLifeCycleTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/FormLifeCycleTest.java @@ -52,7 +52,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class FormLifeCycleTest extends TestResourceLoader{ public FormLifeCycleTest() throws IOException { super(); diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaServiceTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaServiceTest.java new file mode 100644 index 0000000000..9d47b61989 --- /dev/null +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaServiceTest.java @@ -0,0 +1,58 @@ +package org.opensrp.repository.it; + +import static org.mockito.MockitoAnnotations.initMocks; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.opensrp.domain.Multimedia; +import org.opensrp.dto.form.MultimediaDTO; +import org.opensrp.repository.MultimediaRepository; +import org.opensrp.service.MultimediaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.multipart.MultipartFile; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-opensrp.xml") +public class MultimediaServiceTest { + + @Mock + private MultimediaService multimediaService; + + @Autowired + private MultimediaRepository multimediaRepository; + + @Autowired + @Value("#{opensrp['multimedia.directory.name']}") + private String multimediaDirPath; + + @Before + public void setUp() throws Exception + { + initMocks(this); + multimediaService = new MultimediaService(multimediaRepository, multimediaDirPath); + } + + @Test + public void test() { + + } + + +} diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaTest.java new file mode 100644 index 0000000000..2420088d19 --- /dev/null +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/MultimediaTest.java @@ -0,0 +1,146 @@ +package org.opensrp.repository.it; + +import static org.mockito.MockitoAnnotations.initMocks; + +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.imageio.ImageIO; + +import org.apache.commons.io.FilenameUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.ImageType; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.bytedeco.javacpp.opencv_core.IplImage; +import org.bytedeco.javacv.FFmpegFrameGrabber; +import org.bytedeco.javacv.Frame; +import org.bytedeco.javacv.Java2DFrameConverter; +import org.bytedeco.javacv.OpenCVFrameConverter; +import org.bytedeco.javacv.OpenCVFrameGrabber; +import org.jcodec.api.JCodecException; +import org.jcodec.api.awt.FrameGrab; +import org.jcodec.common.FileChannelWrapper; +import org.jcodec.common.NIOUtils; +import org.joda.time.DateTime; +import org.json.JSONException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.runner.RunWith; +import org.mockito.Mock; + +import org.opensrp.domain.Multimedia; +import org.opensrp.repository.MultimediaRepository; +import org.opensrp.service.MultimediaService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext-opensrp.xml") +public class MultimediaTest { + + @Mock + private MultimediaService multimediaService; + + @Autowired + private MultimediaRepository multimediaRepository; + + @Autowired + @Value("#{opensrp['multimedia.directory.name']}") + private String multimediaDirPath; + @Value("#{opensrp['multimedia.datastore.directory']}") + private String basePath; + + @Before + public void setUp() throws Exception + { + initMocks(this); + multimediaService = new MultimediaService(multimediaRepository, multimediaDirPath); + } + + @Ignore @Test + public void shouldSaveMultimediaFile() throws FileNotFoundException, ParseException + { + DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = format.parse("2016-11-11"); + DateTime dateTime=new DateTime(date); + Multimedia multimedia = new Multimedia("immunization form", "22222311", "9","image", null, "png", null, dateTime, "This is An Pilio", null, null, null); + // TODO String status = multimediaService.saveMultimediaFile(CommonsMultipartFile(new FileInputStream("D:\\openSRP_server_workspace\\opensrp-server\\opensrp-web\\src\\test\\resources\\images\\sample.png", multimedia); + // Assert.assertEquals("success", status); + + date = format.parse("2016-11-08"); + dateTime=new DateTime(date); + multimedia = new Multimedia("polio form", "666632888", "5","pdf", null, "pdf", null, dateTime, "This is An Pilio", null, null, null); + // TODO status = multimediaService.saveMultimediaFile("D:\\openSRP_server_workspace\\opensrp-server\\opensrp-web\\src\\test\\resources\\pdf\\immunizationform.pdf", multimedia); + // TODO Assert.assertEquals("success", status); + + date = format.parse("2016-11-11"); + dateTime=new DateTime(date); + multimedia = new Multimedia("chect X-ray", "999995453", "121","image", null, "png", null, dateTime, "This is An chest Scan", null, null, null); + // TODO status = multimediaService.saveMultimediaFile("D:\\openSRP_server_workspace\\opensrp-server\\opensrp-web\\src\\test\\resources\\images\\scan.png", multimedia); + // TODO Assert.assertEquals("success", status); + + } + + @Test + public void shouldGetPagedData() throws FileNotFoundException, JSONException + { + Date date = new Date(); + Assert.assertNotNull( multimediaService.getMultimediaDataByDate(10, new DateTime(date), new DateTime(date))); + } + + @Ignore @Test + public void shouldSaveFrames() throws org.bytedeco.javacv.FrameGrabber.Exception, IOException, JCodecException + { + File file=new File(System.getProperty("user.dir")+"\\video\\video.mp4"); + BufferedImage frame = getFrame(file, 1.0); + ImageIO.write(frame, "png", new File("frame_1.png")); + } + + BufferedImage getFrame(File file, double sec) throws IOException, JCodecException { + FileChannelWrapper ch = null; + try { + ch = NIOUtils.readableFileChannel(file); + return ((FrameGrab) new FrameGrab(ch).seekToSecondPrecise(sec)).getFrame(); + } finally { + NIOUtils.closeQuietly(ch); + } + } + + @Ignore @Test + public void shouldSavePdf() throws IOException + { + PDDocument document = PDDocument.load(new File(System.getProperty("user.dir")+"\\pdf\\pdf_guide.pdf")); + PDFRenderer pdfRenderer = new PDFRenderer(document); + for (int page = 0; page < document.getNumberOfPages(); ++page) + { + BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); + + // suffix in filename will be used as the file format + ImageIO.write(bim, "png", new File("pdfImage_1.png")); + } + document.close(); + } + + +} diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/ScheduleLifeCycleTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/ScheduleLifeCycleTest.java index 82b3c23f44..cd5d5d94a4 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/ScheduleLifeCycleTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/ScheduleLifeCycleTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class ScheduleLifeCycleTest extends TestResourceLoader{ public ScheduleLifeCycleTest() throws IOException { diff --git a/opensrp-core/src/test/java/org/opensrp/repository/it/ZiggyServiceTest.java b/opensrp-core/src/test/java/org/opensrp/repository/it/ZiggyServiceTest.java index 10b23942a9..99d995e21a 100644 --- a/opensrp-core/src/test/java/org/opensrp/repository/it/ZiggyServiceTest.java +++ b/opensrp-core/src/test/java/org/opensrp/repository/it/ZiggyServiceTest.java @@ -30,7 +30,7 @@ import com.google.gson.Gson; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:test-applicationContext-opensrp.xml") +@ContextConfiguration("classpath:applicationContext-opensrp.xml") public class ZiggyServiceTest extends TestResourceLoader{ public ZiggyServiceTest() throws IOException { super(); diff --git a/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml b/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml deleted file mode 100644 index 20976fab43..0000000000 --- a/opensrp-core/src/test/resources/test-applicationContext-opensrp.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/opensrp-form/src/main/java/org/opensrp/form/service/FormAttributeParser.java b/opensrp-form/src/main/java/org/opensrp/form/service/FormAttributeParser.java index 2b3925c42e..19b6ef3011 100644 --- a/opensrp-form/src/main/java/org/opensrp/form/service/FormAttributeParser.java +++ b/opensrp-form/src/main/java/org/opensrp/form/service/FormAttributeParser.java @@ -22,6 +22,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.apache.commons.lang.StringUtils; import org.opensrp.form.domain.FormField; import org.opensrp.form.domain.FormSubmission; import org.opensrp.form.domain.SubFormData; @@ -42,7 +43,6 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; -import com.mysql.jdbc.StringUtils; /** * The class is the bridge that allows parsing and mapping of formSubmission fields with @@ -76,7 +76,7 @@ public FormSubmissionMap createFormSubmissionMap(FormSubmission fs) throws JsonI Map fieldAttributes = bindPath==null?new HashMap():getAttributesForBindPath(bindPath, modelXml); boolean ismultiselect = bindPath==null?false:isMultiselect(bindPath, jsonForm); - if(!StringUtils.isEmptyOrWhitespaceOnly(fsf.value())){ + if(!StringUtils.isBlank(fsf.value())){ if(ismultiselect){ String[] vals = fsf.value().split(" "); Map> valCods = new HashMap<>(); @@ -539,7 +539,7 @@ public Map getAttributesForSubform (String subformName, FormSubm public Map getInstanceAttributesForFormFieldAndValue(String fieldName, String fieldVal, String subform, String formName, JsonObject formDefinition, JsonObject jsonForm) throws JsonSyntaxException, IOException { String bindPath = null; - if(StringUtils.isEmptyOrWhitespaceOnly(subform)){ + if(StringUtils.isBlank(subform)){ bindPath = getPropertyBindFromFormDefinition(fieldName, formName, formDefinition); } else { @@ -552,7 +552,7 @@ public Map getInstanceAttributesForFormFieldAndValue(String fiel public Map getInstanceAttributesForFormFieldAndValue(String fieldName, String fieldVal, String subform, FormSubmission fs) throws JsonSyntaxException, IOException { String bindPath = null; - if(StringUtils.isEmptyOrWhitespaceOnly(subform)){ + if(StringUtils.isBlank(subform)){ bindPath = getPropertyBindFromFormDefinition(fieldName, fs.formName(), getFormDefinitionData(fs.formName())); } else { diff --git a/opensrp-web/pom.xml b/opensrp-web/pom.xml index 2df4985e42..60726e8c9d 100644 --- a/opensrp-web/pom.xml +++ b/opensrp-web/pom.xml @@ -53,6 +53,7 @@ + + @@ -131,7 +132,8 @@ - + --> + @@ -209,31 +211,142 @@ mysql-connector-java ${mysql.connector.version} - - org.springframework.security - spring-security-core - ${spring.version} - - - org.springframework.security - spring-security-web - ${spring.version} - - - org.springframework.security - spring-security-config - ${spring.version} - - - org.springframework - spring-test - ${spring.version} - test + + org.springframework.security + spring-security-core + ${spring.version} - - javax.servlet - jstl - 1.2 + + org.springframework.security + spring-security-web + ${spring.version} + + + org.springframework.security + spring-security-config + ${spring.version} + + + org.springframework + spring-test + ${spring.version} + test + + + javax.servlet + jstl + 1.2 + + + org.apache.pdfbox + pdfbox + 2.0.1 + + + + org.jcodec + jcodec-javase + 0.1.9 + + + org.bytedeco + javacpp + 1.2.1 + + + org.bytedeco.javacpp-presets + opencv + 3.1.0-1.2 + + + org.bytedeco.javacpp-presets + ffmpeg + 3.0.2-1.2 + + + org.bytedeco.javacpp-presets + flycapture + 2.9.3.43-1.2 + + + org.bytedeco.javacpp-presets + libdc1394 + 2.2.4-1.2 + + + org.bytedeco.javacpp-presets + libfreenect + 0.5.3-1.2 + + + org.bytedeco.javacpp-presets + videoinput + 0.200-1.2 + + + org.bytedeco.javacpp-presets + artoolkitplus + 2.3.1-1.2 + + + org.bytedeco.javacpp-presets + chilitags + master-1.2 + + + org.bytedeco.javacpp-presets + flandmark + 1.07-1.2 + + + org.bytedeco.javacpp-presets + fftw + 3.3.4-1.2 + + + org.bytedeco.javacpp-presets + gsl + 2.1-1.2 + + + org.bytedeco.javacpp-presets + llvm + 3.8.0-1.2 + + + org.bytedeco.javacpp-presets + leptonica + 1.73-1.2 + + + org.bytedeco.javacpp-presets + tesseract + 3.04.01-1.2 + + + org.bytedeco.javacpp-presets + caffe + rc3-1.2 + + + org.bytedeco.javacpp-presets + cuda + 7.5-1.2 + + + org.bytedeco.javacpp-presets + mxnet + master-1.2 + + + org.bytedeco.javacpp-presets + tensorflow + 0.8.0-1.2 + + + org.bytedeco + javacv + 1.2 - + diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/ANMLocationController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/ANMLocationController.java deleted file mode 100644 index e5671b62d6..0000000000 --- a/opensrp-web/src/main/java/org/opensrp/web/controller/ANMLocationController.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.opensrp.web.controller; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import org.apache.commons.lang.exception.ExceptionUtils; -import org.opensrp.common.util.HttpAgent; -import org.opensrp.common.util.HttpResponse; -import org.opensrp.dto.VillagesDTO; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import java.text.MessageFormat; - -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.web.bind.annotation.RequestMethod.GET; - -@Controller -public class ANMLocationController { - private static Logger logger = LoggerFactory.getLogger(ANMLocationController.class.toString()); - private final String opensrpANMVillagesURL; - private UserController userController; - private HttpAgent httpAgent; - - @Autowired - public ANMLocationController(@Value("#{opensrp['opensrp.anm.villages.url']}") String opensrpANMVillagesURL, - UserController userController, - HttpAgent httpAgent) { - this.opensrpANMVillagesURL = opensrpANMVillagesURL; - this.userController = userController; - this.httpAgent = httpAgent; - } - - @RequestMapping(method = GET, value = "/anm-villages") - @ResponseBody - public ResponseEntity villagesForANM() { - HttpResponse response = new HttpResponse(false, null); - try { - String anmIdentifier = userController.currentUser().getUsername(); - response = httpAgent.get(opensrpANMVillagesURL + "?anm-id=" + anmIdentifier); - VillagesDTO villagesDTOs = new Gson().fromJson(response.body(), - new TypeToken() { - }.getType()); - logger.info("Fetched Villages for the ANM"); - return new ResponseEntity<>(villagesDTOs, HttpStatus.OK); - } catch (Exception exception) { - logger.error(MessageFormat.format("{0} occurred while fetching Village Details for anm. StackTrace: \n {1}", exception.getMessage(), ExceptionUtils.getFullStackTrace(exception))); - logger.error(MessageFormat.format("Response with status {0} and body: {1} was obtained from {2}", response.isSuccess(), response.body(), opensrpANMVillagesURL)); - } - return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } -} diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/AdminTaskController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/AdminTaskController.java new file mode 100644 index 0000000000..3de2dafc6e --- /dev/null +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/AdminTaskController.java @@ -0,0 +1,35 @@ +package org.opensrp.web.controller; + +import org.motechproject.scheduler.domain.MotechEvent; +import org.opensrp.connector.openmrs.constants.OpenmrsConstants; +import org.opensrp.connector.openmrs.schedule.OpenmrsSyncerListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/adminTasks") +public class AdminTaskController { + private OpenmrsSyncerListener openmrsSync; + private String token; + + @Autowired + public AdminTaskController(@Value("#{opensrp['admin.task.token']}") String token, OpenmrsSyncerListener openmrsSync) { + this.token = token; + this.openmrsSync = openmrsSync; + } + + @RequestMapping("syncDrugs") + public @ResponseBody String syncDrugs(@RequestParam("taskToken") String taskToken) { + if(token.equalsIgnoreCase(taskToken)){ + openmrsSync.pullDataFromOpenMRS(new MotechEvent(OpenmrsConstants.SCHEDULER_OPENMRS_DATA_PULL_SUBJECT)); + return "OK"; + } + else { + return "UNAUTHORIZED"; + } + } +} diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/ErrorTraceController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/ErrorTraceController.java index 4585753444..d7c0a80921 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/controller/ErrorTraceController.java +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/ErrorTraceController.java @@ -1,10 +1,10 @@ /** * @author muhammad.ahmed@ihsinformatics@gmail.com + * and Shakeeb.raza@ihsinformatics.com */ package org.opensrp.web.controller; import java.text.SimpleDateFormat; - import java.util.Date; import java.util.HashMap; import java.util.List; @@ -14,11 +14,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; - import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; - import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; @@ -32,9 +30,9 @@ import static org.springframework.http.HttpStatus.OK; import static org.springframework.web.bind.annotation.RequestMethod.*; +import org.apache.commons.lang3.StringUtils; import org.opensrp.domain.ErrorTrace; import org.opensrp.domain.ErrorTraceForm; - import org.opensrp.service.ErrorTraceService; import com.google.gson.Gson; @@ -53,95 +51,52 @@ public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, false)); } - + + @RequestMapping("/errorhandler") + public String Redirecting(HttpServletRequest request, + ErrorTraceForm errorTraceForm, BindingResult errors) { + return "redirect:/errorhandler/index"; + } + @Autowired public ErrorTraceController(ErrorTraceService errorTraceService) { - this.errorTraceService = errorTraceService; } @RequestMapping(method = GET, value = "/index") public ModelAndView showPage() { - - Map model = new HashMap(); - ErrorTraceForm errorForm=new ErrorTraceForm(); - - Gson gson = new Gson(); - - // - // Convert numbers array into JSON string. - // - String optionsJson = gson.toJson(errorForm.getStatusOptions()); + Gson gson = new Gson(); + String optionsJson = gson.toJson(errorForm.getStatusOptions()); model.put("statusOptions",optionsJson); - model.put("type", "all"); - return new ModelAndView("home_error", model); - } - - @RequestMapping(method = GET, value = "/errortrace") @ResponseBody - public ResponseEntity> allErrors() { - + public ResponseEntity> allErrors(@RequestParam("status") String status) { + List list=null; try { Map model = new HashMap(); - List list = errorTraceService.getAllErrors(); + if(StringUtils.isBlank(status)) + { + list = errorTraceService.getAllError(); + } + else + { + list = errorTraceService.getErrorsByStatus(status); + } model.put("errors", list); - model.put("type", "all"); - - - return new ResponseEntity<>(list, HttpStatus.OK); - } catch (Exception e) { + } catch (Exception e) + { e.printStackTrace(); return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } + } } - - @RequestMapping(method = GET, value = "/unsolvederrors") - @ResponseBody - public ResponseEntity> showUnsolved() { - - try { - Map model = new HashMap(); - List list = errorTraceService.getAllUnsolvedErrors(); - model.put("errors", list); - model.put("type", "unsolved"); - - - return new ResponseEntity<>(list, HttpStatus.OK); - } catch (Exception e) { - e.printStackTrace(); - return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } - } - - @RequestMapping(method = GET, value = "/solvederrors") - @ResponseBody - public ResponseEntity> showSolved() { - - try { - Map model = new HashMap(); - - List list = errorTraceService.getAllSolvedErrors(); - model.put("errors", list); - model.put("type", "solved"); - - return new ResponseEntity<>(list, HttpStatus.OK); - - } catch (Exception e) { - e.printStackTrace(); - return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } - - } - @RequestMapping(method=GET,value="/viewerror") @ResponseBody @@ -150,18 +105,17 @@ public ResponseEntity showError(@RequestParam("id") String id){ ErrorTrace error=errorTraceService.getError(id); - ErrorTraceForm errorTraceForm=new ErrorTraceForm(); + ErrorTraceForm errorTraceForm=new ErrorTraceForm(); errorTraceForm.setErrorTrace(error); System.out.println("error ID :" + errorTraceForm.getErrorTrace().getId()); return new ResponseEntity<>(errorTraceForm, HttpStatus.OK); - - } catch (Exception e) { - e.printStackTrace(); - return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } - + }catch (Exception e) + { + e.printStackTrace(); + return new ResponseEntity<>(INTERNAL_SERVER_ERROR); + } } @@ -169,25 +123,16 @@ public ResponseEntity showError(@RequestParam("id") String id){ @ResponseBody public ResponseEntity> statusOptions(){ try{ - - - - ErrorTraceForm errorTraceForm=new ErrorTraceForm(); - - + ErrorTraceForm errorTraceForm=new ErrorTraceForm(); return new ResponseEntity<>(errorTraceForm.getStatusOptions(), HttpStatus.OK); - } catch (Exception e) { - e.printStackTrace(); - return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } - + }catch (Exception e) + { + e.printStackTrace(); + return new ResponseEntity<>(INTERNAL_SERVER_ERROR); + } } - - - - - /**@author engrmahmed14@gmail.com + /**@authors engrmahmed14@gmail.com and shakeeb.raza@ihsinformatics.com * @return String , value of the view error page * @param ErrorTraceForm * this method uses spring binding for form update . @@ -197,13 +142,9 @@ public ResponseEntity> statusOptions(){ @RequestMapping(value = "/update_errortrace", method = POST) public String updateErrorTrace(HttpServletRequest request, ErrorTraceForm errorTraceForm, BindingResult errors) { - if (errors.hasErrors()) { - - } - + if (errors.hasErrors()) {} System.out.println(errorTraceForm.getErrorTrace().getId()); - ErrorTrace errorTrace = errorTraceService.getError(errorTraceForm - .getErrorTrace().getId()); + ErrorTrace errorTrace = errorTraceService.getError(errorTraceForm.getErrorTrace().getId()); errorTrace.setStatus(errorTraceForm.getErrorTrace().getStatus()); errorTraceService.updateError(errorTrace); // System.out.println("page context :: "+request.getContextPath()); @@ -212,11 +153,9 @@ public String updateErrorTrace(HttpServletRequest request, @RequestMapping(value="/update_status", method=GET) public String UpdateStatus(@RequestParam("id") String id, @RequestParam("status") String status){ - ErrorTrace errorTrace = errorTraceService.getError(id); errorTrace.setStatus(status); errorTraceService.updateError(errorTrace); - return "redirect:/errorhandler/index"; } @@ -224,16 +163,11 @@ public String UpdateStatus(@RequestParam("id") String id, @RequestParam("status" @RequestMapping(method = GET, value = "/allerrors") @ResponseBody public ResponseEntity getAllErrors() { - - List list = errorTraceService.getAllErrors(); + List list = errorTraceService.getAllError(); if (list == null) { - return (ResponseEntity) new ResponseEntity<>( - "No Record(s) Found .", allowOrigin(opensrpSiteUrl), OK); - + return (ResponseEntity) new ResponseEntity<>("No Record(s) Found .", allowOrigin(opensrpSiteUrl), OK); } - return (ResponseEntity) new ResponseEntity<>(list, - allowOrigin(opensrpSiteUrl), OK); - + return (ResponseEntity) new ResponseEntity<>(list,allowOrigin(opensrpSiteUrl), OK); } } diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java index 4c07359de6..a0b6191fa6 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java @@ -170,14 +170,14 @@ public List getFiles(@RequestParam("anm-id") String providerId) { return with(allMultimedias).convert(new Converter() { @Override public MultimediaDTO convert(Multimedia md) { - return new MultimediaDTO(md.getCaseId(), md.getProviderId(), md.getContentType(), md.getFilePath(), md.getFileCategory()); + return new MultimediaDTO(md.getBaseEntityId(), md.getProviderId(), md.getContentType(), md.getFilePath(), md.getFileCategory()); } }); } @RequestMapping(headers = {"Accept=multipart/form-data"}, method = POST, value = "/multimedia-file") public ResponseEntity uploadFiles(@RequestParam("anm-id") String providerId, @RequestParam("entity-id") String entityId,@RequestParam("content-type") String contentType, @RequestParam("file-category") String fileCategory, @RequestParam("file") MultipartFile file) { - MultimediaDTO multimediaDTO = new MultimediaDTO(entityId, providerId, contentType, null, fileCategory); + Multimedia multimediaDTO = new Multimedia(entityId, providerId, contentType, null, fileCategory); String status = multimediaService.saveMultimediaFile(multimediaDTO, file); diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/MultimediaController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/MultimediaController.java new file mode 100644 index 0000000000..abaaf4fe06 --- /dev/null +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/MultimediaController.java @@ -0,0 +1,259 @@ +package org.opensrp.web.controller; + +import static ch.lambdaj.collection.LambdaCollections.with; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.springframework.web.bind.annotation.RequestMethod.GET; +import static org.springframework.web.bind.annotation.RequestMethod.POST; + +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferByte; +import java.io.File; + +import javax.imageio.ImageIO; + +import org.jcodec.api.awt.FrameGrab; +import org.jcodec.common.FileChannelWrapper; +import org.jcodec.common.NIOUtils; +import org.jcodec.common.model.ColorSpace; +import org.jcodec.common.model.Picture; +import org.jcodec.scale.ColorUtil; +import org.jcodec.scale.Transform; + +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URLDecoder; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.imageio.ImageIO; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.rendering.ImageType; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.bytedeco.javacv.FFmpegFrameGrabber; +import org.bytedeco.javacv.Frame; +import org.bytedeco.javacv.Java2DFrameConverter; +import org.bytedeco.javacv.OpenCVFrameGrabber; +import org.jcodec.api.JCodecException; +import org.jcodec.common.NIOUtils; +import org.joda.time.DateTime; +import org.json.JSONException; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.beans.factory.annotation.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.opensrp.service.MultimediaService; +import org.opensrp.domain.*; +import org.opensrp.repository.*; + +import ch.lambdaj.function.convert.Converter; + +import com.google.gson.Gson; + +@Controller +public class MultimediaController { + + private MultimediaService multimediaService; + + private MultimediaRepository multimediaRepository; + + private String basePath; + + @Autowired + public MultimediaController(MultimediaService multimediaService, + MultimediaRepository multimediaRepository, + @Value("#{opensrp['multimedia.datastore.directory']}") String path) { + this.multimediaRepository = multimediaRepository; + this.multimediaService = multimediaService; + this.basePath=path; + } + + @RequestMapping(method = RequestMethod.GET, value = "/multimediaData", produces = "application/json") + @ResponseBody + public List getMultimediaData(HttpServletRequest request, + @RequestParam("searchByName") String searchByName, + @RequestParam("searchByContent") String searchByContent, + @RequestParam("searchByStartDate") String searchByStartDate, + @RequestParam("searchByEndDate") String searchByEndDate, + @RequestParam("length") Integer length) throws Exception { + List temp; + if (!searchByName.isEmpty()) { + temp = multimediaService.getMultimediaDataByName(length, + searchByName); + } else if (!searchByContent.isEmpty()) { + temp = multimediaService.getMultimediaDataByContent(length, + searchByContent); + } else if (!searchByStartDate.isEmpty() && !searchByEndDate.isEmpty()) { + DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date startdate = format.parse(searchByStartDate); + Date enddate = format.parse(searchByEndDate); + DateTime startdateTime = new DateTime(startdate); + DateTime enddateTime = new DateTime(enddate); + + temp = multimediaService.getMultimediaDataByDate(length, + startdateTime, enddateTime); + } else { + temp = multimediaService.getMultimediaData(length); + } + System.out.print(temp); + return temp; + } + + @RequestMapping(value = "/image", method = RequestMethod.GET) + @ResponseBody + public void multimediaImagePreview(@RequestParam("path") String data, + Locale locale, Model model, HttpServletRequest request, + HttpServletResponse response) throws IOException, + org.bytedeco.javacv.FrameGrabber.Exception, JCodecException { + + String filePath = basePath + File.separator + data; + String SendfilePath=""; + System.out.println(); + System.out.println(filePath); + if (data.contains("video")) { + System.out.println(data); + File file = new File(filePath); + BufferedImage frame = getFrame(file, 1.0); + ImageIO.write(frame, "png", new File("frame_1.png")); + System.out.println("\n data:" + data); + filePath="frame_1.png"; + } else if (data.contains("documents")) { + PDDocument document = PDDocument + .load(new File(filePath)); + PDFRenderer pdfRenderer = new PDFRenderer(document); + int page = 0; + BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, + ImageType.RGB); + ImageIO.write(bim, "png", new File("pdfImage_1.png")); + + document.close(); + filePath="pdfImage_1.png"; + } else if (data.contains("images")) { + System.out.println(filePath); + } + int fileSize = (int) new File(filePath).length(); + response.setContentLength(fileSize); + response.setContentType("image/png"); + FileInputStream inputStream = new FileInputStream(filePath); + ServletOutputStream outputStream = response.getOutputStream(); + int value = IOUtils.copy(inputStream, outputStream); + System.out.println("File Size :: " + fileSize); + System.out.println("Copied Bytes :: " + value); + IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(outputStream); + response.setStatus(HttpServletResponse.SC_OK); + + } + + @RequestMapping(value = "/download", method = RequestMethod.GET) + @ResponseBody + public void multimediaDownload(@RequestParam("path") String data, + Locale locale, Model model, HttpServletRequest request, + HttpServletResponse response) throws IOException { + getMultimedia(data, locale, model, request, response); + } + + @RequestMapping(value = "/preview", method = RequestMethod.GET) + @ResponseBody + public void multimediaPreview(@RequestParam("path") String data, + Locale locale, Model model, HttpServletRequest request, + HttpServletResponse response) throws IOException { + getMultimedia(data, locale, model, request, response); + + } + + @RequestMapping(method = RequestMethod.GET, value = "/page") + @ResponseBody + public ModelAndView showPage() throws JSONException { + return new ModelAndView("multimedia_page"); + } + + BufferedImage getFrame(File file, double sec) throws IOException, + JCodecException { + FileChannelWrapper ch = null; + try { + ch = NIOUtils.readableFileChannel(file); + return ((FrameGrab) new FrameGrab(ch).seekToSecondPrecise(sec)) + .getFrame(); + } finally { + NIOUtils.closeQuietly(ch); + } + } + + public void getMultimedia(String data, Locale locale, Model model, + HttpServletRequest request, HttpServletResponse response) + throws IOException { + String filePath = basePath + File.separator + data; + int fileSize = (int) new File(filePath).length(); + response.setContentLength(fileSize); + if (data.contains("video")) + response.setContentType("video/mp4"); + else if (data.contains("image")) + response.setContentType("image/png"); + else if (data.contains("document")) + response.setContentType("application/pdf"); + FileInputStream inputStream = new FileInputStream(filePath); + ServletOutputStream outputStream = response.getOutputStream(); + int value = IOUtils.copy(inputStream, outputStream); + System.out.println("File Size :: " + fileSize); + System.out.println("Copied Bytes :: " + value); + IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(outputStream); + response.setStatus(HttpServletResponse.SC_OK); + } + + @RequestMapping(headers = { "Accept=application/json" }, method = GET, value = "/getmultimedia") + @ResponseBody + public List getMultimediaFiles(@RequestParam("providerId") String providerId) { + + List allMultimedias = multimediaService + .getMultimediaFiles(providerId); + + return with(allMultimedias).convert( + new Converter() { + @Override + public Multimedia convert(Multimedia md) { + return new Multimedia(md.getBaseEntityId(), md + .getProviderId(), md.getContentType(), md + .getFilePath(), md.getFileCategory()); + } + }); + } + + @RequestMapping(headers = { "Accept=multipart/form-data" }, method = POST, value = "/setmultimedia") + public ResponseEntity uploadMultimediaFiles( + @RequestParam("providerId") String providerId, + @RequestParam("entityId") String entityId, + @RequestParam("contentType") String contentType, + @RequestParam("fileCategory") String fileCategory, + @RequestParam("file") MultipartFile file) { + + Multimedia Multimedia = new Multimedia(entityId, providerId, + contentType, null, fileCategory); + + String status = multimediaService.saveMultimediaFile(Multimedia, file); + + return new ResponseEntity<>(new Gson().toJson(status), HttpStatus.OK); + } +} diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/OrderController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/OrderController.java new file mode 100644 index 0000000000..a56892b6b0 --- /dev/null +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/OrderController.java @@ -0,0 +1,86 @@ +package org.opensrp.web.controller; + +import static ch.lambdaj.collection.LambdaCollections.with; +import static java.text.MessageFormat.format; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.CREATED; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.web.bind.annotation.RequestMethod.GET; +import static org.springframework.web.bind.annotation.RequestMethod.POST; + +import java.text.ParseException; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; +import org.opensrp.domain.Drug; +import org.opensrp.common.AllConstants; +import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold; +import org.opensrp.connector.openmrs.service.EncounterService; +import org.opensrp.connector.openmrs.service.HouseholdService; +import org.opensrp.connector.openmrs.service.OpenmrsOrderService; +import org.opensrp.connector.openmrs.service.PatientService; +import org.opensrp.domain.Client; +import org.opensrp.form.domain.*; +import org.opensrp.domain.DrugOrder; +import org.opensrp.domain.ErrorTrace; +import org.opensrp.domain.Event; +import org.opensrp.domain.Multimedia; +import org.opensrp.dto.form.FormSubmissionDTO; +import org.opensrp.dto.form.MultimediaDTO; +import org.opensrp.form.domain.FormSubmission; +import org.opensrp.form.service.FormSubmissionConverter; +import org.opensrp.form.service.FormSubmissionService; +import org.opensrp.repository.AllDrugOrders; +import org.opensrp.repository.AllDrugs; +import org.opensrp.scheduler.SystemEvent; +import org.opensrp.scheduler.TaskSchedulerService; +import org.opensrp.service.ErrorTraceService; +import org.opensrp.service.MultimediaService; +import org.opensrp.service.formSubmission.FormEntityConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans. factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +import ch.lambdaj.function.convert.Converter; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +@Controller +public class OrderController { + private static Logger logger = LoggerFactory.getLogger(OrderController.class.toString()); + private AllDrugs allDrugs; + private AllDrugOrders allDrugOrders; + + @Autowired + public OrderController(AllDrugs allDrugs, AllDrugOrders allDrugOrders) { + this.allDrugs=allDrugs; + this.allDrugOrders = allDrugOrders; + } + + @RequestMapping(method = GET, value="/drugs") + @ResponseBody + private List getAllDrugs() throws JSONException { + List druglist = allDrugs.getAll(); + return druglist; + } + + @RequestMapping(method = GET, value="/drugorders") + @ResponseBody + private List getAllOrders() throws JSONException { + List drugOrderList = allDrugOrders.getAll(); + return drugOrderList; + } + +} diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/ProviderController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/ProviderController.java new file mode 100644 index 0000000000..a6797d21c3 --- /dev/null +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/ProviderController.java @@ -0,0 +1,116 @@ +package org.opensrp.web.controller; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.opensrp.api.domain.User; +import org.opensrp.common.util.HttpAgent; +import org.opensrp.common.util.HttpResponse; +import org.opensrp.domain.Client; +import org.opensrp.domain.Drug; +import org.opensrp.domain.DrugOrder; +import org.opensrp.domain.Event; +import org.opensrp.dto.VillagesDTO; +import org.opensrp.repository.AllDrugOrders; +import org.opensrp.repository.AllDrugs; +import org.opensrp.service.ClientService; +import org.opensrp.service.EventService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.web.bind.annotation.RequestMethod.GET; + +@Controller +public class ProviderController { + private static Logger logger = LoggerFactory.getLogger(ProviderController.class.toString()); + private final String opensrpANMVillagesURL; + private UserController userController; + private HttpAgent httpAgent; + private ClientService clientService; + private EventService eventService; + private AllDrugs allDrugs; + private AllDrugOrders allDrugOrders; + + @Autowired + public ProviderController(@Value("#{opensrp['opensrp.anm.villages.url']}") String opensrpANMVillagesURL, + UserController userController, HttpAgent httpAgent, + ClientService clientService, EventService eventService, AllDrugs allDrugs, AllDrugOrders allDrugOrders) { + this.opensrpANMVillagesURL = opensrpANMVillagesURL; + this.userController = userController; + this.httpAgent = httpAgent; + + this.clientService = clientService; + this.eventService= eventService; + this.allDrugs = allDrugs; + this.allDrugOrders = allDrugOrders; + } + + @RequestMapping(method = GET, value = "/anm-villages") + @ResponseBody + public ResponseEntity villagesForANM() { + HttpResponse response = new HttpResponse(false, null); + try { + String anmIdentifier = userController.currentUser().getUsername(); + response = httpAgent.get(opensrpANMVillagesURL + "?anm-id=" + anmIdentifier); + VillagesDTO villagesDTOs = new Gson().fromJson(response.body(), + new TypeToken() { + }.getType()); + logger.info("Fetched Villages for the ANM"); + return new ResponseEntity<>(villagesDTOs, HttpStatus.OK); + } catch (Exception exception) { + logger.error(MessageFormat.format("{0} occurred while fetching Village Details for anm. StackTrace: \n {1}", exception.getMessage(), ExceptionUtils.getFullStackTrace(exception))); + logger.error(MessageFormat.format("Response with status {0} and body: {1} was obtained from {2}", response.isSuccess(), response.body(), opensrpANMVillagesURL)); + } + return new ResponseEntity<>(INTERNAL_SERVER_ERROR); + } + + @RequestMapping("/assigned-clients-full") + @ResponseBody + public ResponseEntity> assignedClientDataForProvider(@RequestParam("providerId") String providerId) throws JSONException { + Map map = new HashMap<>(); + JSONObject tm = userController.teamAssociation(providerId); + JSONArray patientList = tm.getJSONArray("patients"); + + List clients = new ArrayList<>(); + List events = new ArrayList<>(); + List drugs = new ArrayList<>(); + List drugOrders = new ArrayList<>(); + + for (int i = 0; i < patientList.length(); i++) { + JSONObject patient = patientList.getJSONObject(i); + List cList = clientService.findAllByIdentifier(patient.getString("uuid")); + Client client = cList.isEmpty()?null:cList.get(0); + + if(client != null){ + clients.add(client); + events.addAll(eventService.findByBaseEntityId(client.getBaseEntityId())); + drugs.addAll(allDrugs.getAll()); + drugOrders.addAll(allDrugOrders.findByBaseEntityId(client.getBaseEntityId())); + } + } + + map.put("clients", clients); + map.put("events", events); + map.put("drugs", drugs); + map.put("drugOrders", drugOrders); + return new ResponseEntity<>(map, HttpStatus.OK); + } +} diff --git a/opensrp-web/src/main/java/org/opensrp/web/controller/UserController.java b/opensrp-web/src/main/java/org/opensrp/web/controller/UserController.java index 6dc570824e..264819908f 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/controller/UserController.java +++ b/opensrp-web/src/main/java/org/opensrp/web/controller/UserController.java @@ -62,6 +62,10 @@ public ResponseEntity userDetail(@RequestParam("anm-id") String anmI return new ResponseEntity<>(new UserDetail(user.getUsername(), user.getRoles()), allowOrigin(opensrpSiteUrl), OK); } + public JSONObject teamAssociation(String user) throws JSONException { + return openmrsUserService.getTeamMember(opensrpAuthenticationProvider.getDrishtiUser(user).getAttribute("_PERSON_UUID").toString()); + } + @RequestMapping("/security/authenticate") @ResponseBody public ResponseEntity authenticate() throws JSONException { @@ -69,7 +73,7 @@ public ResponseEntity authenticate() throws JSONException { String lid = ""; JSONObject tm = null; try{ - tm = openmrsUserService.getTeamMember(u.getAttribute("_PERSON_UUID").toString()); + tm = teamAssociation(u.getUsername()); JSONArray locs = tm.getJSONArray("location"); for (int i = 0; i < locs.length(); i++) { lid += locs.getJSONObject(i).getString("uuid")+";;"; diff --git a/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java b/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java index 9eba5c0f94..c71c7b8718 100644 --- a/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java +++ b/opensrp-web/src/main/java/org/opensrp/web/listener/ApplicationStartupListener.java @@ -23,6 +23,7 @@ public class ApplicationStartupListener implements ApplicationListener +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> @@ -25,15 +26,13 @@ rel="stylesheet"> - + - - - -
- OPENSRP +
-

Error Handling -

+

Error Handling

- - - -
+
+
+ + +
+ + diff --git a/opensrp-web/src/main/webapp/WEB-INF/solvederrors.jsp b/opensrp-web/src/main/webapp/WEB-INF/solvederrors.jsp index 5506b078df..5ed1c0de35 100644 --- a/opensrp-web/src/main/webapp/WEB-INF/solvederrors.jsp +++ b/opensrp-web/src/main/webapp/WEB-INF/solvederrors.jsp @@ -39,13 +39,13 @@