diff --git a/assets/config/couchdb.properties b/assets/config/couchdb.properties
index 849574625b..b9a831f2a6 100644
--- a/assets/config/couchdb.properties
+++ b/assets/config/couchdb.properties
@@ -1,3 +1,4 @@
+#this file is used by motech
host=localhost
port=5984
maxConnections=20
diff --git a/assets/config/opensrp.properties b/assets/config/opensrp.properties
index 5964f09f7b..ff773174dd 100644
--- a/assets/config/opensrp.properties
+++ b/assets/config/opensrp.properties
@@ -20,7 +20,7 @@ mcts-report-delay-in-days=10
mcts.poll.time.interval.in.minutes=10
# OpenMRS configuration
-openmrs.url=http://localhost:8181/openmrs/
+openmrs.url=http://localhost:8080/openmrs/
openmrs.username=admin
openmrs.password=Admin123
openmrs.idgen.url=/module/idgen/exportIdentifiers.form
@@ -51,7 +51,7 @@ jdbc.backend=MYSQL
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=VA1913wm
-jdbc.url=jdbc:mysql://localhost:3306/opensrp_tbreach?createDatabaseIfNotExist=true
+jdbc.url=jdbc:mysql://localhost:3306/opensrp?createDatabaseIfNotExist=true
##jdbc url with server and port but without database
jdbc.url-wo-db=jdbc:mysql://localhost:3306
@@ -98,4 +98,4 @@ opensrp.authencation.cache.ttl=600
redis.host=localhost
redis.port=6379
redis.password=RedI$P@S5
-redis.pool.max.connections=25
\ No newline at end of file
+redis.pool.max.connections=25
diff --git a/assets/config/schedule_tracking.properties b/assets/config/schedule_tracking.properties
index e5de3c178a..8526c88542 100644
--- a/assets/config/schedule_tracking.properties
+++ b/assets/config/schedule_tracking.properties
@@ -1 +1,2 @@
+#this file is used by motech
schedule.definitions.directory=/schedules
\ No newline at end of file
diff --git a/assets/migrations/environments/development.properties b/assets/migrations/environments/development.properties
index 3e8e71d1de..770eb8f34b 100644
--- a/assets/migrations/environments/development.properties
+++ b/assets/migrations/environments/development.properties
@@ -82,4 +82,4 @@ core_tablespace_location='/opt/postgres/core'
error_tablespace_location ='/opt/postgres/error'
schedule_tablespace_location='/opt/postgres/schedule'
feed_tablespace_location='/opt/postgres/feed'
-form_tablespace_location='/opt/postgres/form'
\ No newline at end of file
+form_tablespace_location='/opt/postgres/form'
diff --git a/build/maven.properties b/build/maven.properties
index 41a4367a9c..68d6a6d379 100644
--- a/build/maven.properties
+++ b/build/maven.properties
@@ -1,16 +1,16 @@
#database configuration that is not likely to change unless massive refactoring
-couchdb.db.opensrp=opensrp_tbreach
-couchdb.db.form=opensrp-form_tbreach
-couchdb.db.atomfeed=atomfeed_tbreach
-couchdb.db.mcts=opensrp-mcts_tbreach
-couchdb.db.motech-scheduletracking=motech-scheduletracking-api_tbreach
-couchdb.db.error=opensrp-errortrace_tbreach
+couchdb.db.opensrp=opensrp
+couchdb.db.form=opensrp-form
+couchdb.db.atomfeed=atomfeed
+couchdb.db.mcts=opensrp-mcts
+couchdb.db.motech-scheduletracking=motech-scheduletracking-api
+couchdb.db.error=opensrp-errortrace
-db.quartz=motechquartz_tbreach
-db.reporting=opensrp_tbreach
-db.reporting.report=report_tbreach
-db.reporting.anm=anm_report_tbreach
+db.quartz=motechquartz
+db.reporting=opensrp
+db.reporting.report=report
+db.reporting.anm=anm_report
#selenium
diff --git a/opensrp-common/pom.xml b/opensrp-common/pom.xml
index 85ba887814..afcbafe31f 100644
--- a/opensrp-common/pom.xml
+++ b/opensrp-common/pom.xml
@@ -120,6 +120,10 @@
2.3
test
-
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java b/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java
index 1beda5bff4..04aff2d300 100644
--- a/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java
+++ b/opensrp-common/src/main/java/org/opensrp/common/util/CustomCertificateSSLSocketFactory.java
@@ -30,7 +30,7 @@ public CustomCertificateSSLSocketFactory(KeyStore truststore) throws NoSuchAlgor
super(truststore);
System.setProperty("disable_bad_sslciphers", "yes");
- System.setProperty("jsse.enableSNIExtension", "false");
+ System.setProperty("jsse.enableSNIExtension", "true");
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/HostNameSetter.java b/opensrp-common/src/main/java/org/opensrp/common/util/HostNameSetter.java
new file mode 100644
index 0000000000..c0b8f37c3d
--- /dev/null
+++ b/opensrp-common/src/main/java/org/opensrp/common/util/HostNameSetter.java
@@ -0,0 +1,77 @@
+package org.opensrp.common.util;
+
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.net.ssl.SSLSocket;
+
+public class HostNameSetter {
+
+ private static final AtomicReference CURRENT = new AtomicReference<>();
+
+ private final WeakReference> cls;
+ private final WeakReference setter;
+
+ private HostNameSetter(Class> clazz, Method setter) {
+ this.cls = new WeakReference<>(clazz);
+ this.setter = setter == null ? null : new WeakReference<>(setter);
+ }
+
+ private static Method init(Class> cls) {
+ Method s = null;
+ try {
+ s = cls.getMethod("setHost", String.class);
+ } catch (Exception e) {
+ initFail(e);
+ }
+ CURRENT.set(new HostNameSetter(cls, s));
+ return s;
+ }
+
+ private static void initFail(Exception e) {
+ // ignore
+ }
+
+ private Method reuse(Class> cls) {
+ final boolean wrongClass = this.cls.get() != cls;
+ if (wrongClass) {
+ return init(cls);
+ }
+
+ final boolean setterNotSupported = this.setter == null;
+ if (setterNotSupported) {
+ return null;
+ }
+
+ final Method s = setter.get();
+ final boolean setterLost = s == null;
+ return setterLost ? init(cls) : s;
+ }
+
+ /**
+ * Invokes the {@code #setName(String)} method if one is present.
+ *
+ * @param hostname
+ * the name to set
+ * @param sslsock
+ * the socket
+ */
+ public static void setServerNameIndication(String hostname, SSLSocket sslsock) {
+ final Class> cls = sslsock.getClass();
+ final HostNameSetter current = CURRENT.get();
+ final Method setter = (current == null) ? init(cls) : current.reuse(cls);
+ if (setter != null) {
+ try {
+ setter.invoke(sslsock, hostname);
+ } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
+ setServerNameIndicationFail(e);
+ }
+ }
+ }
+
+ private static void setServerNameIndicationFail(Exception e) {
+ // ignore
+ }
+}
\ No newline at end of file
diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java b/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java
index 318ce544b9..112a582aba 100644
--- a/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java
+++ b/opensrp-common/src/main/java/org/opensrp/common/util/HttpUtil.java
@@ -1,185 +1,177 @@
package org.opensrp.common.util;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
-import org.apache.http.client.methods.*;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.conn.scheme.PlainSocketFactory;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.conn.scheme.SchemeRegistry;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.DefaultRedirectStrategy;
+import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.KeyStore;
-
@Component
public class HttpUtil {
-
- private HttpUtil() {
-
- }
-
- public enum AuthType {
- BASIC, TOKEN, NONE
- }
-
- private final static DefaultHttpClient httpClient = init();
-
- public static DefaultHttpClient init() {
- try {
- //TODO add option to ignore cetificate validation in opensrp.prop
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null, null);
- CustomCertificateSSLSocketFactory sf = new CustomCertificateSSLSocketFactory(trustStore);
- sf.setHostnameVerifier(CustomCertificateSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
-
- BasicHttpParams basicHttpParams = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(basicHttpParams, 30000);
- HttpConnectionParams.setSoTimeout(basicHttpParams, 60000);
-
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", sf, 443));
-
- ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(basicHttpParams, registry);
- return new DefaultHttpClient(connectionManager, basicHttpParams);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
-
- public static HttpResponse post(String url, String payload, String data, String username, String password) {
- return post(url, payload, data, "application/json", AuthType.BASIC, username + ":" + password);
- }
-
- public static HttpResponse post(String url, String payload, String data) {
- return post(url, payload, data, "application/json", AuthType.NONE, "");
- }
-
- public static HttpResponse postWithToken(String url, String payload, String data, String token) {
- return post(url, payload, data, "application/json", AuthType.TOKEN, token);
- }
-
- //TODO: Move setting content type in makeConnection function.
- public static HttpResponse post(String url, String payload, String data, String contentType, AuthType authType, String authString) {
- try {
- HttpPost request = (HttpPost) makeConnection(url, payload, RequestMethod.POST, authType, authString);
- request.setHeader(HTTP.CONTENT_TYPE, contentType);
- StringEntity entity = new StringEntity(data == null ? "" : data);
- System.out.println(data);
- entity.setContentEncoding(contentType);
- request.setEntity(entity);
- org.apache.http.HttpResponse response = httpClient.execute(request);
- return createCustomResponseFrom(response);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
-
- public static HttpResponse get(String url, String payload, String username, String password) {
- return get(url, payload, AuthType.BASIC, username + ":" + password);
- }
-
- public static HttpResponse delete(String url, String payload, String username, String password) {
- return delete(url, payload, AuthType.BASIC, username + ":" + password);
- }
-
- public static HttpResponse get(String url, String payload) {
- return get(url, payload, AuthType.NONE, "");
- }
-
- public static HttpResponse getWithToken(String url, String payload, String token) {
- return get(url, payload, AuthType.BASIC, token);
- }
-
- public static HttpResponse get(String url, String payload, AuthType authType, String authString) {
- try {
- HttpGet request = (HttpGet) makeConnection(url, payload, RequestMethod.GET, authType, authString);
- org.apache.http.HttpResponse response = httpClient.execute(request);
- return createCustomResponseFrom(response);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static HttpResponse delete(String url, String payload, AuthType authType, String authString) {
- try {
- HttpDelete request = (HttpDelete) makeConnection(url, payload, RequestMethod.DELETE, authType, authString);
- org.apache.http.HttpResponse response = httpClient.execute(request);
- return createCustomResponseFrom(response);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- static HttpResponse createCustomResponseFrom(org.apache.http.HttpResponse response) throws IOException {
- int statusCode = response.getStatusLine().getStatusCode();
- String entity = "";
- if (response.getEntity() != null) {
- entity = IOUtils.toString(response.getEntity().getContent());
- }
-
- return new HttpResponse(checkSuccessBasedOnHttpCode(statusCode), statusCode, entity);
- }
-
- static boolean checkSuccessBasedOnHttpCode(int httpCode) {
- if (httpCode >= 400 && httpCode <= 599) {
- return false;
- } else {
- return true;
- }
- }
-
- static HttpRequestBase makeConnection(String url, String payload, RequestMethod method, AuthType authType, String authString) throws URISyntaxException {
- String charset = "UTF-8";
-
- if (url.endsWith("/")) {
- url = url.substring(0, url.lastIndexOf("/"));
- }
- url = (url + (StringUtils.isBlank(payload) ? "" : ("?" + payload))).replaceAll(" ", "%20");
- URI urlo = new URI(url);
-
- HttpRequestBase requestBase = null;
- if (method.equals(RequestMethod.GET)) {
- requestBase = new HttpGet(urlo);
- } else if (method.equals(RequestMethod.POST)) {
- requestBase = new HttpPost(urlo);
- } else if (method.equals(RequestMethod.PUT)) {
- requestBase = new HttpPut(urlo);
- } else if (method.equals(RequestMethod.DELETE)) {
- requestBase = new HttpDelete(urlo);
- }
- requestBase.setURI(urlo);
- requestBase.addHeader("Accept-Charset", charset);
-
- if (authType.name().equalsIgnoreCase("basic")) {
- String encoded = authString.matches(".+:.+") ? new String(Base64.encodeBase64(authString.getBytes())) : authString;
- requestBase.addHeader("Authorization", "Basic " + encoded);
- } else if (authType.name().equalsIgnoreCase("token")) {
- requestBase.addHeader("Authorization", "Token " + authString);
- }
-
- System.out.println(url);
- return requestBase;
- }
-
- public static String removeEndingSlash(String str) {
- return str.endsWith("/") ? str.substring(0, str.lastIndexOf("/")) : str;
- }
-
- public static String removeTrailingSlash(String str) {
- return str.startsWith("/") ? str.substring(1) : str;
- }
+ private HttpUtil() {
+
+ }
+
+ public enum AuthType {
+ BASIC, TOKEN, NONE
+ }
+
+ private static CloseableHttpClient init(String host) {
+ try {
+
+ HttpClientBuilder clientBuilder = HttpClientBuilder.create();
+ ServerNameIndicationSSLContext ctx = new ServerNameIndicationSSLContext(
+ host, 443);
+ clientBuilder.setSSLContext(ctx);
+ clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy());
+ return clientBuilder.build();
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static HttpResponse post(String url, String payload, String data, String username, String password) {
+ return post(url, payload, data, "application/json", AuthType.BASIC, username + ":" + password);
+ }
+
+ public static HttpResponse post(String url, String payload, String data) {
+ return post(url, payload, data, "application/json", AuthType.NONE, "");
+ }
+
+ public static HttpResponse postWithToken(String url, String payload, String data, String token) {
+ return post(url, payload, data, "application/json", AuthType.TOKEN, token);
+ }
+
+ public static HttpResponse post(String url, String payload, String data, String contentType, AuthType authType,
+ String authString) {
+ try {
+ HttpPost request = (HttpPost) makeConnection(url, payload, RequestMethod.POST, authType, authString);
+ request.setHeader(HTTP.CONTENT_TYPE, contentType);
+ StringEntity entity = new StringEntity(data == null ? "" : data);
+ System.out.println(data);
+ entity.setContentEncoding(contentType);
+ request.setEntity(entity);
+ CloseableHttpClient httpClient = init(request.getURI().getHost());
+ org.apache.http.HttpResponse response = httpClient.execute(request);
+ return createCustomResponseFrom(response);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static HttpResponse get(String url, String payload, String username, String password) {
+ return get(url, payload, AuthType.BASIC, username + ":" + password);
+ }
+
+ public static HttpResponse delete(String url, String payload, String username, String password) {
+ return delete(url, payload, AuthType.BASIC, username + ":" + password);
+ }
+
+ public static HttpResponse get(String url, String payload) {
+ return get(url, payload, AuthType.NONE, "");
+ }
+
+ public static HttpResponse getWithToken(String url, String payload, String token) {
+ return get(url, payload, AuthType.BASIC, token);
+ }
+
+ public static HttpResponse get(String url, String payload, AuthType authType, String authString) {
+ try {
+ HttpGet request = (HttpGet) makeConnection(url, payload, RequestMethod.GET, authType, authString);
+ CloseableHttpClient httpClient = init(request.getURI().getHost());
+ org.apache.http.HttpResponse response = httpClient.execute(request);
+ return createCustomResponseFrom(response);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static HttpResponse delete(String url, String payload, AuthType authType, String authString) {
+ try {
+ HttpDelete request = (HttpDelete) makeConnection(url, payload, RequestMethod.DELETE, authType, authString);
+ CloseableHttpClient httpClient = init(request.getURI().getHost());
+ org.apache.http.HttpResponse response = httpClient.execute(request);
+ return createCustomResponseFrom(response);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ static HttpResponse createCustomResponseFrom(org.apache.http.HttpResponse response) throws IOException {
+ int statusCode = response.getStatusLine().getStatusCode();
+ String entity = "";
+ if (response.getEntity() != null) {
+ entity = IOUtils.toString(response.getEntity().getContent());
+ }
+
+ return new HttpResponse(checkSuccessBasedOnHttpCode(statusCode), statusCode, entity);
+ }
+
+ static boolean checkSuccessBasedOnHttpCode(int httpCode) {
+ if (httpCode >= 400 && httpCode <= 599) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ static HttpRequestBase makeConnection(String url, String payload, RequestMethod method, AuthType authType,
+ String authString) throws URISyntaxException {
+ String charset = "UTF-8";
+
+ if (url.endsWith("/")) {
+ url = url.substring(0, url.lastIndexOf("/"));
+ }
+ url = (url + (StringUtils.isBlank(payload) ? "" : ("?" + payload))).replaceAll(" ", "%20");
+ URI urlo = new URI(url);
+
+ HttpRequestBase requestBase = null;
+ if (method.equals(RequestMethod.GET)) {
+ requestBase = new HttpGet(urlo);
+ } else if (method.equals(RequestMethod.POST)) {
+ requestBase = new HttpPost(urlo);
+ } else if (method.equals(RequestMethod.PUT)) {
+ requestBase = new HttpPut(urlo);
+ } else if (method.equals(RequestMethod.DELETE)) {
+ requestBase = new HttpDelete(urlo);
+ }
+ requestBase.setURI(urlo);
+ requestBase.addHeader("Accept-Charset", charset);
+
+ if (authType.name().equalsIgnoreCase("basic")) {
+ String encoded = authString.matches(".+:.+") ? new String(Base64.encodeBase64(authString.getBytes()))
+ : authString;
+ requestBase.addHeader("Authorization", "Basic " + encoded);
+ } else if (authType.name().equalsIgnoreCase("token")) {
+ requestBase.addHeader("Authorization", "Token " + authString);
+ }
+
+ System.out.println(url);
+ return requestBase;
+ }
+
+ public static String removeEndingSlash(String str) {
+ return str.endsWith("/") ? str.substring(0, str.lastIndexOf("/")) : str;
+ }
+
+ public static String removeTrailingSlash(String str) {
+ return str.startsWith("/") ? str.substring(1) : str;
+ }
}
diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContext.java b/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContext.java
new file mode 100644
index 0000000000..ce9dcd6640
--- /dev/null
+++ b/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContext.java
@@ -0,0 +1,36 @@
+package org.opensrp.common.util;
+
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SNIHostName;
+import javax.net.ssl.SNIServerName;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+
+public class ServerNameIndicationSSLContext extends SSLContext {
+
+ String hostname;
+
+ public ServerNameIndicationSSLContext(String hostname, int port) {
+ super(new ServerNameIndicationSSLContextSpi(hostname, port), null, "Default");
+ this.hostname = hostname;
+ }
+
+ public SSLParameters getParametersForSNI() {
+ SSLParameters params = null;
+ try {
+ params = SSLContext.getDefault().getDefaultSSLParameters();
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+
+ List sNIServerNameList = new ArrayList();
+ sNIServerNameList.add(new SNIHostName(hostname));
+ params.setServerNames(sNIServerNameList);
+ params.setEndpointIdentificationAlgorithm("HTTPS");
+ return params;
+ }
+
+}
\ No newline at end of file
diff --git a/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContextSpi.java b/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContextSpi.java
new file mode 100644
index 0000000000..c29913406d
--- /dev/null
+++ b/opensrp-common/src/main/java/org/opensrp/common/util/ServerNameIndicationSSLContextSpi.java
@@ -0,0 +1,81 @@
+package org.opensrp.common.util;
+
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLContextSpi;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+
+public class ServerNameIndicationSSLContextSpi extends SSLContextSpi {
+
+ private final String hostname;
+ private final int port;
+
+ public ServerNameIndicationSSLContextSpi(String hostname, int port) {
+ this.hostname = hostname;
+ this.port = port;
+ }
+
+ @Override
+ protected void engineInit(KeyManager[] keyManagers, TrustManager[] trustManagers, SecureRandom secureRandom)
+ throws KeyManagementException {
+
+ }
+
+ @Override
+ protected SSLSocketFactory engineGetSocketFactory() {
+ try {
+ return SSLContext.getDefault().getSocketFactory();
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ protected SSLServerSocketFactory engineGetServerSocketFactory() {
+ try {
+ return SSLContext.getDefault().getServerSocketFactory();
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ protected SSLEngine engineCreateSSLEngine() {
+ try {
+ return SSLContext.getDefault().createSSLEngine(hostname, port);
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ protected SSLEngine engineCreateSSLEngine(String host, int port) {
+ try {
+ return SSLContext.getDefault().createSSLEngine(host, port);
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ protected SSLSessionContext engineGetServerSessionContext() {
+ return null;
+ }
+
+ @Override
+ protected SSLSessionContext engineGetClientSessionContext() {
+ return null;
+ }
+}
diff --git a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java
index e3116f50a6..fc09781a49 100644
--- a/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java
+++ b/opensrp-connector/src/main/java/org/opensrp/connector/openmrs/service/EncounterService.java
@@ -20,386 +20,417 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.mysql.jdbc.StringUtils;
@Service
public class EncounterService extends OpenmrsService {
-
- public static final String OPENMRS_UUID_IDENTIFIER_TYPE = "OPENMRS_UUID";
-
- private static final String ENCOUNTER_URL = "ws/rest/v1/encounter";//"ws/rest/emrapi/encounter";
-
- private static final String OBS_URL = "ws/rest/v1/obs";
-
- private static final String ENCOUNTER__TYPE_URL = "ws/rest/v1/encountertype";
-
- private PatientService patientService;
-
- private OpenmrsUserService userService;
-
- private ClientService clientService;
-
- private OpenmrsLocationService openmrsLocationService;
-
- @Autowired
- public EncounterService(PatientService patientService, OpenmrsUserService userService, ClientService clientService,
- OpenmrsLocationService openmrsLocationService) {
- this.patientService = patientService;
- this.userService = userService;
- this.clientService = clientService;
- this.openmrsLocationService = openmrsLocationService;
- }
-
- public EncounterService(String openmrsUrl, String user, String password) {
- super(openmrsUrl, user, password);
- }
-
- public PatientService getPatientService() {
- return patientService;
- }
-
- public void setPatientService(PatientService patientService) {
- this.patientService = patientService;
- }
-
- public OpenmrsUserService getUserService() {
- return userService;
- }
-
- public void setUserService(OpenmrsUserService userService) {
- this.userService = userService;
- }
-
- public JSONObject getEncounterByUuid(String uuid, boolean noRepresentationTag) throws JSONException {
- return new JSONObject(HttpUtil.get(getURL() + "/" + ENCOUNTER_URL + "/" + uuid, noRepresentationTag ? "" : "v=full",
- OPENMRS_USER, OPENMRS_PWD).body());
- }
-
- public JSONObject getObsByEncounterUuid(String encounterUuid) throws JSONException {
- // The data format returned contains the obs uuid and concept uuids
- return new JSONObject(HttpUtil.get(getURL() + "/" + ENCOUNTER_URL + "/" + encounterUuid,
- "v=custom:(uuid,obs:(uuid,concept:(uuid)))", OPENMRS_USER, OPENMRS_PWD).body());
- }
-
- public JSONObject getObsUuidByParentObsUuid(String obsUuid) throws JSONException {
- //The data format returned contains the children obs uuid and concept uuids
- return new JSONObject(HttpUtil.get(getURL() + "/" + OBS_URL + "/" + obsUuid,
- "v=custom:(groupMembers:(uuid,concept:(uuid)))", OPENMRS_USER, OPENMRS_PWD).body());
- }
-
- public JSONObject getEncounterType(String encounterType) throws JSONException {
- // we have to use this ugly approach because identifier not found throws exception and
- // its hard to find whether it was network error or object not found or server error
- JSONObject resEncounterType = new JSONObject(
- HttpUtil.get(getURL() + "/" + ENCOUNTER__TYPE_URL, "v=full", OPENMRS_USER, OPENMRS_PWD).body());
-
- if (resEncounterType.has("results") && resEncounterType.get("results") instanceof JSONArray) {
- JSONArray res = resEncounterType.getJSONArray("results");
- for (int i = 0; i < res.length(); i++) {
- if (res.getJSONObject(i).getString("display").equalsIgnoreCase(encounterType)) {
- return res.getJSONObject(i);
- }
- }
- }
- return null;
- }
-
- public JSONObject createEncounterType(String name, String description) throws JSONException {
- JSONObject o = convertEncounterToOpenmrsJson(name, description);
- return new JSONObject(
- HttpUtil.post(getURL() + "/" + ENCOUNTER__TYPE_URL, "", o.toString(), OPENMRS_USER, OPENMRS_PWD).body());
- }
-
- public JSONObject convertEncounterToOpenmrsJson(String name, String description) throws JSONException {
- JSONObject a = new JSONObject();
- a.put("name", name);
- a.put("description", description);
- return a;
- }
-
- public JSONObject createEncounter(Event e) throws JSONException {
- String ptuuid = patientService.getPatientByIdentifierUUID(e.getBaseEntityId());
- if (ptuuid == null) {
- return null;
- }
- JSONObject enc = new JSONObject();
-
- String pruuid = userService.getPersonUUIDByUser(e.getProviderId());
-
- enc.put("encounterDatetime", OPENMRS_DATE.format(e.getEventDate().toDate()));
- // patient must be existing in OpenMRS before it submits an encounter. if it doesnot it would throw NPE
- enc.put("patient", ptuuid);
- //TODO enc.put("patientUuid", pt.getString("uuid"));
- enc.put("encounterType", e.getEventType());
- //TODO enc.put("encounterTypeUuid", e.getEventType());
- enc.put("location", e.getLocationId());
- enc.put("provider", pruuid);
-
- List ol = e.getObs();
- Map p = new HashMap<>();
- Map pc = new HashMap<>();
-
- if (ol != null)
- for (Obs obs : ol) {
- if (!StringUtils.isEmptyOrWhitespaceOnly(obs.getFieldCode())
- && (obs.getFieldType() == null || obs.getFieldType().equalsIgnoreCase("concept"))) {
- // skipping empty obs and fields that don't have concepts if no parent simply make it root obs
-
- if (obs.getFieldType().equals("concept") && obs.getFormSubmissionField().equals("Birth_Facility_Name")
- && obs.getValue() != null) {
- Location location = openmrsLocationService.getLocation(obs.getValue().toString());
- if (location != null && location.getName() != null) {
- obs.setValue(location.getName());
- }
- }
- if (StringUtils.isEmptyOrWhitespaceOnly(obs.getParentCode())) {
- p.put(obs.getFieldCode(), convertObsToJson(obs));
- } else {
- //find parent obs if not found search and fill or create one
- JSONArray parentObs = p.get(obs.getParentCode());
- if (parentObs == null) {
- p.put(obs.getParentCode(), convertObsToJson(getOrCreateParent(ol, obs)));
- }
- // find if any other exists with same parent if so add to the list otherwise create new list
- JSONArray obl = pc.get(obs.getParentCode());
- if (obl == null) {
- obl = new JSONArray();
- }
- JSONArray addobs = convertObsToJson(obs);
- for (int i = 0; i < addobs.length(); i++) {
- obl.put(addobs.getJSONObject(i));
- }
- pc.put(obs.getParentCode(), obl);
- }
- }
- }
-
- JSONArray obar = new JSONArray();
- for (String ok : p.keySet()) {
- for (int i = 0; i < p.get(ok).length(); i++) {
- JSONObject obo = p.get(ok).getJSONObject(i);
-
- JSONArray cob = pc.get(ok);
- if (cob != null && cob.length() > 0) {
- obo.put("groupMembers", cob);
- }
-
- obar.put(obo);
- }
- }
- enc.put("obs", obar);
-
- HttpResponse op = HttpUtil.post(HttpUtil.removeEndingSlash(OPENMRS_BASE_URL) + "/" + ENCOUNTER_URL, "",
- enc.toString(), OPENMRS_USER, OPENMRS_PWD);
- return new JSONObject(op.body());
- }
-
- public JSONObject buildUpdateEncounter(Event e) throws JSONException {
- String openmrsuuid = e.getIdentifier(OPENMRS_UUID_IDENTIFIER_TYPE);
- JSONObject encounterObsUuids = getObsByEncounterUuid(openmrsuuid);
- JSONArray obsUuids = encounterObsUuids.getJSONArray("obs");
-
- System.out.print("[OBS-UUIDS]" + obsUuids);
-
- String ptuuid = patientService.getPatientByIdentifierUUID(e.getBaseEntityId());//TODO find by any identifier
- JSONObject enc = new JSONObject();
-
- String pruuid = userService.getPersonUUIDByUser(e.getProviderId());
-
- enc.put("encounterDatetime", OPENMRS_DATE.format(e.getEventDate().toDate()));
- // patient must be existing in OpenMRS before it submits an encounter. if it doesnot it would throw NPE
- enc.put("patient", ptuuid);
- //TODO enc.put("patientUuid", pt.getString("uuid"));
- enc.put("encounterType", e.getEventType());
- enc.put("location", e.getLocationId());
- enc.put("provider", pruuid == null ? "" : pruuid);
-
- List ol = e.getObs();
- Map p = new HashMap<>();
- Map pc = new HashMap<>();
-
- if (ol != null)
- for (Obs obs : ol) {
- if (!StringUtils.isEmptyOrWhitespaceOnly(obs.getFieldCode())
- && (obs.getFieldType() == null || obs.getFieldType().equalsIgnoreCase("concept"))) {
- //skipping empty obs if no parent simply make it root obs
- if (obs.getFieldType().equals("concept") && obs.getFormSubmissionField().equals("Birth_Facility_Name")
- && obs.getValue() != null
- && openmrsLocationService.getLocation(obs.getValue().toString()).getName() != null) {
- obs.setValue(openmrsLocationService.getLocation(obs.getValue().toString()).getName());
- }
- if (StringUtils.isEmptyOrWhitespaceOnly(obs.getParentCode())) {
- p.put(obs.getFieldCode(), convertObsToJson(obs));
- } else {
- //find parent obs if not found search and fill or create one
- JSONArray parentObs = p.get(obs.getParentCode());
- if (parentObs == null) {
- p.put(obs.getParentCode(), convertObsToJson(getOrCreateParent(ol, obs)));
- }
- // find if any other exists with same parent if so add to the list otherwise create new list
- JSONArray obl = pc.get(obs.getParentCode());
- if (obl == null) {
- obl = new JSONArray();
- }
- JSONArray addobs = convertObsToJson(obs);
- for (int i = 0; i < addobs.length(); i++) {
- obl.put(addobs.getJSONObject(i));
- }
- pc.put(obs.getParentCode(), obl);
- }
- }
- }
-
- JSONArray obar = new JSONArray();
- for (String ok : p.keySet()) {
- for (int i = 0; i < p.get(ok).length(); i++) {
- JSONObject obo = p.get(ok).getJSONObject(i);
- obo.put("uuid", getObsUuid(obo, obsUuids));
-
- JSONArray cob = pc.get(ok);
- if (cob != null && cob.length() > 0) {
- // Fetch children obs uuids
- JSONObject obsGroupUuids = getObsUuidByParentObsUuid(obo.getString("uuid"));
- JSONArray groupUuids = obsGroupUuids.getJSONArray("groupMembers");
- // Add uuids to group members
- for (int j = 0; j < cob.length(); j++) {
- JSONObject cobObj = cob.getJSONObject(j);
- cobObj.put("uuid", getObsUuid(cobObj, groupUuids));
- }
-
- obo.put("groupMembers", cob);
- }
-
- obar.put(obo);
- }
- }
- enc.put("obs", obar);
-
- return enc;
- }
-
- public JSONObject updateEncounter(Event e) throws JSONException {
- if (StringUtils.isEmptyOrWhitespaceOnly(e.getIdentifier(OPENMRS_UUID_IDENTIFIER_TYPE))) {
- throw new IllegalArgumentException("Encounter was never pushed to OpenMRS as " + OPENMRS_UUID_IDENTIFIER_TYPE
- + " is empty. Consider creating a new one");
- }
-
- String openmrsuuid = e.getIdentifier(OPENMRS_UUID_IDENTIFIER_TYPE);
-
- JSONObject enc = buildUpdateEncounter(e);
-
- HttpResponse op = HttpUtil.post(
- HttpUtil.removeEndingSlash(OPENMRS_BASE_URL) + "/" + ENCOUNTER_URL + "/" + openmrsuuid, "", enc.toString(),
- OPENMRS_USER, OPENMRS_PWD);
- return new JSONObject(op.body());
- }
-
- private String getObsUuid(JSONObject obs, JSONArray obsUuids) throws JSONException {
- String uuid = "";
- // obs = {"concept":"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
- // obsUuids = [{"concept":{"uuid":"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},"uuid":"b267b2f5-94be-43e8-85c4-4e36f2eb8471"}, {}]
-
- for (int i = 0; i < obsUuids.length(); i++) {
- JSONObject obsUuid = obsUuids.getJSONObject(i);
- JSONObject conceptObj = obsUuid.getJSONObject("concept");
-
- if (conceptObj.get("uuid").equals(obs.get("concept"))) {
- return obsUuid.getString("uuid");
- }
- }
-
- return uuid;
- }
-
- private JSONArray convertObsToJson(Obs o) throws JSONException {
- JSONArray arr = new JSONArray();
- if (o.getValues() == null || o.getValues().size() == 0) {//must be parent of some obs
- JSONObject obo = new JSONObject();
- obo.put("concept", o.getFieldCode());
-
- arr.put(obo);
- } else {
- //OpenMRS can not handle multivalued obs so add obs with multiple values as two different obs
- for (Object v : o.getValues()) {
- JSONObject obo = new JSONObject();
- obo.put("concept", o.getFieldCode());
- obo.put("value", v);
-
- arr.put(obo);
- }
- }
- return arr;
- }
-
- private Obs getOrCreateParent(List obl, Obs o) {
- for (Obs obs : obl) {
- if (o.getParentCode().equalsIgnoreCase(obs.getFieldCode())) {
- return obs;
- }
- }
- return new Obs("concept", "parent", o.getParentCode(), null, null, null, null);
- }
-
- // TODO needs review and refactor
- public Event convertToEvent(JSONObject encounter) throws JSONException {
- if (encounter.has("patient") == false) {
- throw new IllegalStateException("No 'patient' object found in given encounter");
- }
- Event e = new Event();
- String patientUuid = encounter.getJSONObject("patient").getString("uuid");
- Client c = clientService.find(patientUuid);
- if (c == null || c.getBaseEntityId() == null) {
- //try to get the client from openmrs based on the uuid
- JSONObject openmrsPatient = patientService.getPatientByUuid(patientUuid, false);
- c = patientService.convertToClient(openmrsPatient);
- if (c == null || c.getBaseEntityId() == null) {
- throw new IllegalStateException(
- "Client was not found registered while converting Encounter to an Event in OpenSRP");
- } else {
- clientService.addClient(c);
- }
- }
-
- JSONObject creator = encounter.getJSONObject("auditInfo").getJSONObject("creator");
- e.withBaseEntityId(c.getBaseEntityId())
- .withCreator(new User(creator.getString("uuid"), creator.getString("display"), null, null))
- .withDateCreated(DateTime.now());
-
- e.withEventDate(new DateTime(encounter.getString("encounterDatetime")))
- //.withEntityType(entityType) //TODO
- .withEventType(encounter.getJSONObject("encounterType").getString("name"))
- //.withFormSubmissionId(formSubmissionId)//TODO
- .withLocationId((encounter.has("location") && encounter.get("location") instanceof JSONObject)
- ? encounter.getJSONObject("location").getString("name")
- : "")
- //TODO manage providers and uuid in couch
- .withProviderId(creator.getString("display")).withVoided(encounter.getBoolean("voided"));
-
- e.addIdentifier(OPENMRS_UUID_IDENTIFIER_TYPE, encounter.getString("uuid"));
-
- JSONArray ol = encounter.getJSONArray("obs");
- for (int i = 0; i < ol.length(); i++) {
- JSONObject o = ol.getJSONObject(i);
- List