Guest User

Untitled

a guest
Nov 28th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.69 KB | None | 0 0
  1. package org.jembi.rhea.module.rheashradapter.util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStreamWriter;
  8. import java.io.Serializable;
  9. import java.net.URL;
  10. import java.security.KeyManagementException;
  11. import java.security.KeyStore;
  12. import java.security.KeyStoreException;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.security.cert.CertificateException;
  15. import java.text.SimpleDateFormat;
  16. import java.util.Date;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.Map.Entry;
  20. import java.util.UUID;
  21.  
  22. import javax.net.ssl.HttpsURLConnection;
  23. import javax.net.ssl.SSLContext;
  24. import javax.net.ssl.SSLSocketFactory;
  25. import javax.net.ssl.TrustManagerFactory;
  26.  
  27. import org.apache.commons.io.IOUtils;
  28. import org.apache.commons.logging.Log;
  29. import org.apache.commons.logging.LogFactory;
  30. import org.jembi.rhea.api.LogEncounterService;
  31. import org.openmrs.Cohort;
  32. import org.openmrs.Encounter;
  33. import org.openmrs.Patient;
  34. import org.openmrs.Person;
  35. import org.openmrs.PersonAttribute;
  36. import org.openmrs.api.context.Context;
  37. import org.openmrs.hl7.HL7Constants;
  38.  
  39. import ca.uhn.hl7v2.HL7Exception;
  40. import ca.uhn.hl7v2.model.v25.datatype.CE;
  41. import ca.uhn.hl7v2.model.v25.message.ORU_R01;
  42. import ca.uhn.hl7v2.model.v25.segment.MSH;
  43. import ca.uhn.hl7v2.model.v25.segment.OBR;
  44. import ca.uhn.hl7v2.model.v25.segment.OBX;
  45. import ca.uhn.hl7v2.model.v25.segment.PID;
  46. import ca.uhn.hl7v2.model.v25.segment.PV1;
  47.  
  48. import javax.xml.bind.DatatypeConverter;
  49. import javax.xml.transform.TransformerException;
  50. import javax.xml.transform.TransformerFactoryConfigurationError;
  51.  
  52. public class GenerateORU_R01Alert implements Serializable {
  53.  
  54. private Log log = LogFactory.getLog(this.getClass());
  55.  
  56. public static String username = Context.getAdministrationService().getGlobalProperty("RHEASHRadapter-omod.hie.username");
  57. public static String password = Context.getAdministrationService().getGlobalProperty("RHEASHRadapter-omod.hie.password");
  58.  
  59. private LogEncounterService service = Context
  60. .getService(LogEncounterService.class);
  61.  
  62. public static String hostname = Context.getAdministrationService().getGlobalProperty("RHEASHRadapter-omod.hie.url");
  63.  
  64. public static SSLSocketFactory sslFactory;
  65.  
  66. private static final long serialVersionUID = 1L;
  67. private ORU_R01 r01 = new ORU_R01();
  68.  
  69. public ORU_R01 generateORU_R01Message(Encounter encounter) throws Exception {
  70.  
  71. MSH msh = r01.getMSH();
  72.  
  73. // Get current date
  74. String dateFormat = "yyyyMMddHHmmss";
  75. SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
  76. String formattedDate = formatter.format(new Date());
  77.  
  78. msh.getFieldSeparator().setValue(RHEAHL7Constants.FIELD_SEPARATOR);//
  79. msh.getEncodingCharacters().setValue(
  80. RHEAHL7Constants.ENCODING_CHARACTERS);//
  81. msh.getVersionID().getInternationalizationCode().getIdentifier()
  82. .setValue(RHEAHL7Constants.INTERNATIONALIZATION_CODE);//
  83. msh.getVersionID().getVersionID().setValue(RHEAHL7Constants.VERSION);//
  84. msh.getDateTimeOfMessage().getTime().setValue(formattedDate);//
  85. msh.getSendingApplication()
  86. .getNamespaceID()
  87. .setValue("316");
  88. msh.getSendingFacility().getNamespaceID().setValue("RwandaMOH");//
  89. msh.getMessageType().getMessageCode()
  90. .setValue(RHEAHL7Constants.MESSAGE_TYPE);//
  91. msh.getMessageType().getTriggerEvent()
  92. .setValue(RHEAHL7Constants.TRIGGER_EVENT);//
  93. msh.getMessageType().getMessageStructure()
  94. .setValue(RHEAHL7Constants.MESSAGE_STRUCTURE);//
  95. msh.getReceivingFacility().getNamespaceID()
  96. .setValue(RHEAHL7Constants.RECEIVING_FACILITY);//
  97. msh.getProcessingID().getProcessingID()
  98. .setValue(RHEAHL7Constants.PROCESSING_ID);//
  99. msh.getProcessingID().getProcessingMode()
  100. .setValue(RHEAHL7Constants.PROCESSING_MODE);//
  101. msh.getMessageControlID().setValue(UUID.randomUUID().toString());//
  102.  
  103. msh.getAcceptAcknowledgmentType().setValue(RHEAHL7Constants.ACK_TYPE);
  104. msh.getApplicationAcknowledgmentType().setValue(
  105. RHEAHL7Constants.APPLICATION_ACK_TYPE);
  106. msh.getMessageProfileIdentifier(0).getEntityIdentifier()
  107. .setValue("ALERT");
  108.  
  109. Cohort singlePatientCohort = new Cohort();
  110. singlePatientCohort.addMember(encounter.getPatient().getId());
  111.  
  112. Map<Integer, String> patientIdentifierMap = Context
  113. .getPatientSetService().getPatientIdentifierStringsByType(
  114. singlePatientCohort,
  115. Context.getPatientService()
  116. .getPatientIdentifierTypeByName(
  117. RHEAHL7Constants.IDENTIFIER_TYPE));
  118.  
  119. PID pid = r01.getPATIENT_RESULT().getPATIENT().getPID();
  120.  
  121. pid.getPatientIdentifierList(0)
  122. .getIDNumber()
  123. .setValue(
  124. patientIdentifierMap.get(patientIdentifierMap.keySet()
  125. .iterator().next()));
  126. pid.getPatientIdentifierList(0).getIdentifierTypeCode()
  127. .setValue(RHEAHL7Constants.IDENTIFIER_TYPE);
  128. pid.getPatientName(0).getFamilyName().getSurname()
  129. .setValue(encounter.getPatient().getFamilyName());
  130. pid.getPatientName(0).getGivenName()
  131. .setValue(encounter.getPatient().getGivenName());
  132.  
  133. // gender
  134. // pid.getAdministrativeSex().setValue(pat.getGender());
  135.  
  136. // dob
  137. Date dob = encounter.getPatient().getBirthdate();
  138. String dobStr = "";
  139. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  140. dobStr = sdf.format(dob);
  141. pid.getDateTimeOfBirth().getTime().setValue(dobStr);
  142.  
  143. PV1 pv1 = r01.getPATIENT_RESULT().getPATIENT().getVISIT().getPV1();
  144.  
  145. pv1.getPatientClass().setValue(RHEAHL7Constants.PATIENT_CLASS);
  146.  
  147. if(encounter.getLocation() != null){
  148. pv1.getAssignedPatientLocation().getFacility().getNamespaceID()
  149. .setValue(encounter.getLocation().getName());
  150. }
  151.  
  152. pv1.getAssignedPatientLocation().getPointOfCare()
  153. .setValue("364");
  154. pv1.getAdmissionType().setValue("ALERT");
  155.  
  156. //Map<Integer, String> providerIdentifierMap = null;
  157.  
  158. //pv1.getAttendingDoctor(0).getIDNumber().setValue("e8597a14-436f-1031-8b61-8d373bf4f88f");
  159. pv1.getAttendingDoctor(0).getIDNumber().setValue(service.getPersonAttributesByPerson(encounter.getProvider(), "EPID"));
  160.  
  161. pv1.getAttendingDoctor(0).getFamilyName().getSurname()
  162. .setValue(encounter.getProvider().getFamilyName());
  163. pv1.getAttendingDoctor(0).getGivenName()
  164. .setValue(encounter.getProvider().getGivenName());
  165. pv1.getAdmitDateTime()
  166. .getTime()
  167. .setValue(
  168. new SimpleDateFormat("yyyyMMddhhmm").format(encounter
  169. .getDateCreated()));
  170.  
  171. pv1.getAttendingDoctor(0).getIdentifierTypeCode().setValue("EPID");
  172.  
  173. r01 = createOBRSegment(r01);
  174.  
  175. return r01;
  176.  
  177. }
  178.  
  179. private ORU_R01 createOBRSegment(ORU_R01 r01) throws HL7Exception {
  180. OBR obr = null;
  181.  
  182. obr = r01.getPATIENT_RESULT().getORDER_OBSERVATION(0).getOBR();
  183. obr.getSetIDOBR().setValue(String.valueOf(0));
  184.  
  185. obr.getUniversalServiceIdentifier().getText().setValue("ALERT");
  186.  
  187. OBX obx = r01.getPATIENT_RESULT().getORDER_OBSERVATION(0)
  188. .getOBSERVATION(0).getOBX();
  189.  
  190. obx.getSetIDOBX().setValue("0");
  191.  
  192. obx.getObservationIdentifier().getIdentifier().setValue("rsms_rm");
  193. obx.getObservationIdentifier().getText().setValue("rsms_rm REMINDER");
  194. obx.getObservationIdentifier().getNameOfCodingSystem().setValue("RSMS");
  195.  
  196. obx.getValueType().setValue(HL7Constants.HL7_CODED);
  197. CE ce = new CE(r01);
  198. ce.getText().setValue("rsms_pmr PATIENT MISSED REFERRAL");
  199. ce.getIdentifier().setValue("rsms_pmr");
  200. ce.getNameOfCodingSystem().setValue("RSMS");
  201.  
  202. obx.getObservationValue(0).setData(ce);
  203.  
  204. return r01;
  205.  
  206. }
  207.  
  208. public void sendRequest(String msg, Encounter e) throws IOException,
  209. TransformerFactoryConfigurationError, TransformerException,
  210. KeyStoreException, NoSuchAlgorithmException, CertificateException,
  211. KeyManagementException {
  212. // Get the key store that includes self-signed cert as a "trusted"
  213. // entry.
  214. InputStream keyStoreStream = GenerateORU_R01Alert.class
  215. .getResourceAsStream("/truststore-prod.jks");
  216.  
  217. // Load the keyStore
  218.  
  219. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  220. keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
  221. log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
  222. keyStoreStream.close();
  223.  
  224. TrustManagerFactory tmf = TrustManagerFactory
  225. .getInstance(TrustManagerFactory.getDefaultAlgorithm());
  226. tmf.init(keyStore);
  227.  
  228. SSLContext ctx = SSLContext.getInstance("TLS");
  229. ctx.init(null, tmf.getTrustManagers(), null);
  230.  
  231. // set SSL Factory to be used for all HTTPS connections
  232. sslFactory = ctx.getSocketFactory();
  233.  
  234. callQueryFacility(msg, e);
  235.  
  236. }
  237.  
  238. private static void addHTTPBasicAuthProperty(HttpsURLConnection conn) {
  239. String userpass = username + ":" + password;
  240. @SuppressWarnings("restriction")
  241. String basicAuth = "Basic "
  242. + new String(DatatypeConverter.printBase64Binary(userpass
  243. .getBytes()));
  244. conn.setRequestProperty("Authorization", basicAuth);
  245. }
  246.  
  247. public String callQueryFacility(String msg, Encounter e) throws IOException,
  248. TransformerFactoryConfigurationError, TransformerException {
  249.  
  250. Cohort singlePatientCohort = new Cohort();
  251. singlePatientCohort.addMember(e.getPatient().getId());
  252.  
  253. Map<Integer, String> patientIdentifierMap = Context.getPatientSetService().getPatientIdentifierStringsByType(
  254. singlePatientCohort,
  255. Context.getPatientService().getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));
  256.  
  257. // Setup connection
  258. String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
  259. URL url = new URL(hostname + "/ws/rest/v1/alerts");
  260. System.out.println("full url " + url);
  261. HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  262. conn.setDoOutput(true);
  263. conn.setRequestMethod("POST");
  264. conn.setDoInput(true);
  265.  
  266. // This is important to get the connection to use our trusted
  267. // certificate
  268. conn.setSSLSocketFactory(sslFactory);
  269.  
  270. addHTTPBasicAuthProperty(conn);
  271. // conn.setConnectTimeout(timeOut);
  272. OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
  273. log.error("body" + msg);
  274. out.write(msg);
  275. out.close();
  276. conn.connect();
  277. String headerValue = conn.getHeaderField("http.status");
  278.  
  279. // Test response code
  280. if (conn.getResponseCode() != 200) {
  281. throw new IOException(conn.getResponseMessage());
  282. }
  283.  
  284. String result = convertInputStreamToString(conn.getInputStream());
  285. conn.disconnect();
  286.  
  287. return result;
  288. }
  289.  
  290. private static String convertInputStreamToString(InputStream is)
  291. throws IOException {
  292. // Buffer the result into a string
  293. BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  294. StringBuilder sb = new StringBuilder();
  295. String line;
  296. while ((line = rd.readLine()) != null) {
  297. sb.append(line + "\n");
  298. }
  299. rd.close();
  300. return sb.toString();
  301. }
  302.  
  303. }
Add Comment
Please, Sign In to add comment