Java Code Examples for ca.uhn.hl7v2.HL7Exception

The following are top voted examples for showing how to use ca.uhn.hl7v2.HL7Exception. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: HL7Receiver   File: PSQLReader.java   View source code 6 votes vote down vote up
@Override
public Message next() throws IOException, HL7Exception {
    Message ret = null;

    while (psqlReaderNextmsg != null && ret == null) {
        Message nextMsg = psqlReaderNextmsg;
        readNextPsqlMessage();

        if (skipMessages) {
            Terser nextMsgTerser = new Terser(nextMsg);
            String currMSH10 = nextMsgTerser.get("/MSH-10");
            if (lastSuccessSendMsgId.compareTo(currMSH10) == 0) {
                LOG.info("Skip message (for the last time):" + currMSH10);
                skipMessages = false;
            } else {
                LOG.info("Skip message:" + currMSH10);
            }
        } else {
            ret = nextMsg;
        }
    }

    return ret;
}
 
Example 2
Project: HL7Receiver   File: PSQLReader.java   View source code 6 votes vote down vote up
private void readNextPsqlMessage() throws IOException, HL7Exception {
    psqlReaderNextmsg = null;
    String strLine;
    while ((strLine = psqlReader.readLine()) != null)   {
        //LOG.info("read line=>" + strLine);
        if (strLine.trim().startsWith("MSH")) {
            //LOG.info("Found msg=>" + strLine);
            String adjustedMsg = strLine.trim().replaceAll("\\\\r","\r\n");
            DefaultHapiContext ctx = new DefaultHapiContext();
            PipeParser pp = ctx.getPipeParser();
            pp.setValidationContext(new NoValidation());
            psqlReaderNextmsg = pp.parse(adjustedMsg);
        }
        if (psqlReaderNextmsg != null) {
            return;
        }
    }
}
 
Example 3
Project: HL7Receiver   File: HAPIReader.java   View source code 6 votes vote down vote up
@Override
public Message next() throws HL7Exception {
    Message ret = null;

    while (hapiIter.hasNext() && ret == null) {
        Message nextMsg = hapiIter.next();
        if (skipMessages) {
            Terser nextMsgTerser = new Terser(nextMsg);
            String currMSH10 = nextMsgTerser.get("/MSH-10");
            if (lastSuccessSendMsgId.compareTo(currMSH10) == 0) {
                LOG.info("Skip message (for the last time):" + currMSH10);
                skipMessages = false;
            } else {
                LOG.info("Skip message:" + currMSH10);
            }
        } else {
            ret = nextMsg;
        }
    }

    return ret;
}
 
Example 4
Project: ccow   File: ContextState.java   View source code 6 votes vote down vote up
public long startSessionChanges(final long participantCoupon) {

		if (!participants.containsKey("" + participantCoupon))
			throw new RuntimeException("Unknown participant something");

		if (transactionIDcalledContextCoupon != null) {
			throw new RuntimeException("Active context is already progress");
		}
		owner = participants.get("" + participantCoupon);
		try {
			cxContainer = new CX(pp.parse(DUMMY_MESSAGE));
		} catch (final HL7Exception e) {
			logger.error(e.getMessage(), e);
		}
		return transactionIDcalledContextCoupon = new Random().nextLong();
	}
 
Example 5
Project: Camel   File: HL7ValidateTest.java   View source code 6 votes vote down vote up
@Test
public void testMarshalWithValidation() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:end");
    mock.expectedMessageCount(0);

    Message message = createADT01Message();
    try {
        template.sendBody("direct:start1", message);
        fail("Should have thrown exception");
    } catch (CamelExecutionException e) {
        assertIsInstanceOf(HL7Exception.class, e.getCause());
        assertIsInstanceOf(ValidationException.class, e.getCause().getCause());
        System.out.println(e.getCause().getCause().getMessage());
        assertTrue("Should be a validation error message", e.getCause().getCause().getMessage().startsWith("Validation failed:"));
    }

    assertMockEndpointsSatisfied();
}
 
Example 6
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 6 votes vote down vote up
protected Map<String,PatientId> extractInternalPatientIds() throws HL7Exception {
	Map<String,PatientId> ids = new LinkedHashMap<String,PatientId>();
	int x=0;
	while(true) {
		String identifier = t.get("PID-3("+x+")-1");
		String authority = t.get("PID-3("+x+")-4");
		String typeId = t.get("PID-3("+x+")-5");

		if(identifier != null) {
			PatientId tmp = new PatientId(identifier, authority, typeId);
			if(typeId.equals("MR") && authority.equals("ST01L")) {
				x++;
				continue;
			}
			ids.put(typeId,tmp);
		}

		if(identifier == null && t.get("PID-3("+(x+1)+")-1")==null) {
			break;
		}
		x++;
	}
	return ids;
}
 
Example 7
Project: Camel   File: TerserLanguage.java   View source code 6 votes vote down vote up
public static Expression terser(final String expression) {
    ObjectHelper.notNull(expression, "expression");
    return new ExpressionAdapter() {

        @Override
        public Object evaluate(Exchange exchange) {
            Message message = exchange.getIn().getBody(Message.class);
            try {
                return new Terser(message).get(expression.trim());
            } catch (HL7Exception e) {
                throw ObjectHelper.wrapRuntimeCamelException(e);
            }
        }

        @Override
        public String toString() {
            return "terser(" + expression + ")";
        }

    };
}
 
Example 8
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 6 votes vote down vote up
protected String getHealthCardRenewDate() throws HL7Exception {
	int x=0;
	while(true) {
		String identifier = t.get("PID-3("+x+")-1");
		//String authority = t.get("PID-3("+x+")-4");
		String typeId = t.get("PID-3("+x+")-5");
		String renewDate = t.get("PID-3("+x+")-8");
		//String ver = t.get("PID-3("+x+")-10");


		if(identifier == null && t.get("PID-3("+(x+1)+")-1")==null) {
			break;
		}

		if(typeId != null && typeId.equals("JHN")) {
			return renewDate;
		}
		x++;
	}
	return null;
}
 
Example 9
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 6 votes vote down vote up
protected Map<String,StaffId> extractStaffIds() throws HL7Exception {
	Map<String,StaffId> ids = new LinkedHashMap<String,StaffId>();
	int x=0;
	while(true) {
		String identifier = t.get("/MF_STAFF/STF-2("+x+")-1");
		String typeCode = t.get("/MF_STAFF/STF-2("+x+")-3");

		if(identifier == null)
			break;

		StaffId tmp = new StaffId(identifier, typeCode);
		ids.put(typeCode,tmp);
		x++;
	}
	return ids;
}
 
Example 10
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 6 votes vote down vote up
protected void extractAdditionalDemographicData() throws HL7Exception {
	logger.info("PD1");

	try {
		t.get("/PD1-4-1");
	}catch(HL7Exception e) {logger.error(e);return;}
	logger.info("PD1-1");
	String practionerId = t.get("/PD1-4-1");
	String practionerLastName = this.extractOrEmpty("/PD1-4-2");
	String practionerFirstName = this.extractOrEmpty("/PD1-4-3");
	String practionerMiddleName = this.extractOrEmpty("/PD1-4-4");

	logger.debug("Additional Demographic");
	logger.debug("practionerId="+practionerId);
	logger.debug("practioner name="+ practionerLastName + "," + practionerFirstName + " " + practionerMiddleName);

}
 
Example 11
Project: OSCAR-ConCert   File: HHSEmrDownloadHandler.java   View source code 6 votes vote down vote up
protected Map<String,PatientId> extractInternalPatientIds() throws HL7Exception {
	Map<String,PatientId> ids = new LinkedHashMap<String,PatientId>();
	int x=0;
	while(true) {
		String identifier = terser.get("PID-3("+x+")-1");
		String authority = terser.get("PID-3("+x+")-4");
		String typeId = terser.get("PID-3("+x+")-5");

		if(identifier != null) {
			PatientId tmp = new PatientId(identifier, authority, typeId);
			ids.put(typeId,tmp);
		}

		if(identifier == null && terser.get("PID-3("+(x+1)+")-1")==null) {
			break;
		}
		x++;
	}
	return ids;
}
 
Example 12
Project: OSCAR-ConCert   File: ContentRenderingServlet.java   View source code 6 votes vote down vote up
private Content getOruR01Content(HttpServletRequest request, LoggedInInfo loggedInInfo) throws EncodingNotSupportedException, UnsupportedEncodingException, HL7Exception {
   // for OruR01 we need segmentId.
String segmentId=request.getParameter("segmentId");
   
   ViewOruR01UIBean viewOruR01UIBean=new ViewOruR01UIBean(segmentId);
   if (!viewOruR01UIBean.hasBinaryFile())
   {
   	logger.error("Odd, this request should not have taken place, there's no binary content.", new IllegalStateException());
   	return(null);
  	}
   
   Content content=new Content();
   content.contentType=getServletContext().getMimeType(viewOruR01UIBean.getFilename());
   content.data=viewOruR01UIBean.getFileContents();
   
   LogAction.addLog(loggedInInfo.getLoggedInProviderNo(), getClass().getSimpleName(), "getOruR01Content", "segmentId="+segmentId);
   
   return(content);
  }
 
Example 13
Project: OSCAR-ConCert   File: OmpO09.java   View source code 6 votes vote down vote up
private static void fillTq1(OMP_O09_ORDER order, Drug drug) throws HL7Exception {
	OMP_O09_TIMING timing = order.getTIMING(0);
	TQ1 tq1 = timing.getTQ1();

	CQ cq = tq1.getQuantity();
	NM quantity = cq.getQuantity();
	quantity.setValue(drug.getQuantity());
	CWE units = cq.getUnits();
	units.getText().setValue(drug.getUnit());
	units.getNameOfCodingSystem().setValue(drug.getUnitName());

	RPT rpt = tq1.getRepeatPattern(0);
	rpt.getGeneralTimingSpecification().setValue(drug.getFreqCode());

	CQ serviceDuration = tq1.getServiceDuration();
	serviceDuration.getQuantity().setValue(drug.getDuration());
	serviceDuration.getUnits().getNameOfCodingSystem().setValue(drug.getDurUnit());

	tq1.getStartDateTime().setValue(DataTypeUtils.getAsHl7FormattedString(drug.getRxDate()));
	tq1.getEndDateTime().setValue(DataTypeUtils.getAsHl7FormattedString(drug.getEndDate()));
}
 
Example 14
Project: OSCAR-ConCert   File: DataTypeUtils.java   View source code 6 votes vote down vote up
/**
 * @param prd
 * @param provider
 * @param providerRoleId Note that this is not the oscar provider role, look in the method to see valid values
 * @param providerRoleDescription Note that this is not the oscar provider role, look in the method to see valid values
 */
public static void fillPrd(PRD prd, Provider provider, String providerRoleId, String providerRoleDescription, Clinic clinic) throws DataTypeException, HL7Exception {
	// Value Description
	// -----------------
	// RP Referring Provider
	// PP Primary Care Provider
	// CP Consulting Provider
	// RT Referred to Provider
	prd.getProviderRole(0).getIdentifier().setValue(providerRoleId);
	prd.getProviderRole(0).getText().setValue(providerRoleDescription);

	XPN xpn = prd.getProviderName(0);
	xpn.getFamilyName().getSurname().setValue(provider.getLastName());
	xpn.getGivenName().setValue(provider.getFirstName());
	xpn.getPrefixEgDR().setValue(provider.getTitle());

	XAD xad = prd.getProviderAddress(0);
	fillXAD(xad, clinic, null, "O");

	XTN xtn = prd.getProviderCommunicationInformation(0);
	xtn.getUnformattedTelephoneNumber().setValue(provider.getWorkPhone());
	xtn.getCommunicationAddress().setValue(provider.getEmail());

	PLN pln = prd.getProviderIdentifiers(0);
	pln.getIDNumber().setValue(provider.getProviderNo());
}
 
Example 15
Project: OSCAR-ConCert   File: DataTypeUtils.java   View source code 6 votes vote down vote up
/**
 * @return a detached and non-persisted Provider model object with data filed in from the PRD.
 * @throws HL7Exception
 */
public static Provider parsePrdAsProvider(PRD prd) throws HL7Exception {
	Provider provider = new Provider();

	XPN xpn = prd.getProviderName(0);
	provider.setLastName(StringUtils.trimToNull(xpn.getFamilyName().getSurname().getValue()));
	provider.setFirstName(StringUtils.trimToNull(xpn.getGivenName().getValue()));
	provider.setTitle(StringUtils.trimToNull(xpn.getPrefixEgDR().getValue()));

	XAD xad = prd.getProviderAddress(0);
	provider.setAddress(StringUtils.trimToNull(xad.getStreetAddress().getStreetOrMailingAddress().getValue()));

	XTN xtn = prd.getProviderCommunicationInformation(0);
	provider.setWorkPhone(StringUtils.trimToNull(xtn.getUnformattedTelephoneNumber().getValue()));
	provider.setEmail(StringUtils.trimToNull(xtn.getCommunicationAddress().getValue()));

	PLN pln = prd.getProviderIdentifiers(0);
	provider.setProviderNo(StringUtils.trimToNull(pln.getIDNumber().getValue()));

	return (provider);
}
 
Example 16
Project: OSCAR-ConCert   File: DataTypeUtils.java   View source code 6 votes vote down vote up
public static ProfessionalSpecialist parsePrdAsProfessionalSpecialist(PRD prd) throws HL7Exception {
	ProfessionalSpecialist professionalSpecialist = new ProfessionalSpecialist();

	XPN xpn = prd.getProviderName(0);
	professionalSpecialist.setLastName(StringUtils.trimToNull(xpn.getFamilyName().getSurname().getValue()));
	professionalSpecialist.setFirstName(StringUtils.trimToNull(xpn.getGivenName().getValue()));
	professionalSpecialist.setProfessionalLetters(StringUtils.trimToNull(xpn.getPrefixEgDR().getValue()));

	XAD xad = prd.getProviderAddress(0);
	professionalSpecialist.setStreetAddress(StringUtils.trimToNull(xad.getStreetAddress().getStreetOrMailingAddress().getValue()));

	XTN xtn = prd.getProviderCommunicationInformation(0);
	professionalSpecialist.setPhoneNumber(StringUtils.trimToNull(xtn.getUnformattedTelephoneNumber().getValue()));
	professionalSpecialist.setEmailAddress(StringUtils.trimToNull(xtn.getCommunicationAddress().getValue()));

	return (professionalSpecialist);
}
 
Example 17
Project: OSCAR-ConCert   File: DataTypeUtils.java   View source code 6 votes vote down vote up
/**
 * The provider returned is just a detached/unmanaged Provider object which may not represent an entry in the db, it is used as a data structure only.
 * 
 * @throws HL7Exception
 */
public static Provider parseRolAsProvider(ROL rol) throws HL7Exception {
	Provider provider = new Provider();

	XCN xcn = rol.getRolePerson(0);
	provider.setProviderNo(StringUtils.trimToNull(xcn.getIDNumber().getValue()));
	provider.setLastName(StringUtils.trimToNull(xcn.getFamilyName().getSurname().getValue()));
	provider.setFirstName(StringUtils.trimToNull(xcn.getGivenName().getValue()));
	provider.setTitle(StringUtils.trimToNull(xcn.getPrefixEgDR().getValue()));

	XAD xad = rol.getOfficeHomeAddressBirthplace(0);
	provider.setAddress(StringUtils.trimToNull(xad.getStreetAddress().getStreetOrMailingAddress().getValue()));

	XTN xtn = rol.getPhone(0);
	provider.setPhone(StringUtils.trimToNull(xtn.getUnformattedTelephoneNumber().getValue()));
	provider.setEmail(StringUtils.trimToNull(xtn.getCommunicationAddress().getValue()));

	return (provider);
}
 
Example 18
Project: OSCAR-ConCert   File: OruR01.java   View source code 6 votes vote down vote up
/**
 * This method is essentially used to make an ORU_R01 containing pretty much any random data.
 * @throws UnsupportedEncodingException 
 */
public static ORU_R01 makeOruR01(Clinic clinic, Demographic demographic, ObservationData observationData, Provider sendingProvider, ProfessionalSpecialist receivingProfessionalSpecialist) throws HL7Exception, UnsupportedEncodingException {
	ORU_R01 observationMsg = new ORU_R01();

	DataTypeUtils.fillMsh(observationMsg.getMSH(), new Date(), clinic.getClinicName(), "ORU", "R01", "ORU_R01", DataTypeUtils.HL7_VERSION_ID);
	DataTypeUtils.fillSft(observationMsg.getSFT(), OscarProperties.getBuildTag(), OscarProperties.getBuildDate());

	ORU_R01_PATIENT_RESULT patientResult = observationMsg.getPATIENT_RESULT(0);
	DataTypeUtils.fillPid(patientResult.getPATIENT().getPID(), 1, demographic);

	ORU_R01_ORDER_OBSERVATION orderObservation = patientResult.getORDER_OBSERVATION(0);
	fillBlankOBR(orderObservation.getOBR());
	fillNtesWithObservationData(orderObservation, observationData);

	// use ROL for the sending and receiving provider
	DataTypeUtils.fillRol(orderObservation.getROL(0), sendingProvider, clinic, DataTypeUtils.ACTION_ROLE_SENDER);
	DataTypeUtils.fillRol(orderObservation.getROL(1), receivingProfessionalSpecialist, DataTypeUtils.ACTION_ROLE_RECEIVER);

	return (observationMsg);
}
 
Example 19
Project: OSCAR-ConCert   File: RefI12.java   View source code 6 votes vote down vote up
public static String getNteValue(REF_I12 referralMsg, REF_NTE_TYPE nteType) throws HL7Exception, UnsupportedEncodingException
{
	logger.debug("Looking for nte comment type : "+nteType.name());
	logger.debug("Number of NTE segments : "+referralMsg.getNTEReps());
	for (int i=0; i<referralMsg.getNTEReps(); i++)
	{
           NTE nte=referralMsg.getNTE(i);
           String nteCommentType=nte.getCommentType().getText().getValue();

           logger.debug("NTE segment type : "+nteCommentType);

           if (nteType.name().equals(nteCommentType))
           {
           	return(new String(DataTypeUtils.getNteCommentsAsSingleDecodedByteArray(nte), MiscUtils.DEFAULT_UTF8_ENCODING));
           }
	}
	
	return(null);
}
 
Example 20
Project: OSCAR-ConCert   File: RefI12.java   View source code 6 votes vote down vote up
/**
 * Get the first PRD entry with the matching providerRoleId, the id is the 2 letter abbreviation.
 * Value Description
 * -----------------
 * RP Referring Provider
 * PP Primary Care Provider
 * CP Consulting Provider
 * RT Referred to Provider
 */
public static PRD getPrdByRoleId(REF_I12 referralMsg, String providerRoleId) throws HL7Exception
{
	logger.debug("Looking for prd roleId : "+providerRoleId);
	logger.debug("Number of prd segments : "+referralMsg.getPROVIDER_CONTACTReps());
	for (int i=0; i<referralMsg.getPROVIDER_CONTACTReps(); i++)
	{
           PRD prd=referralMsg.getPROVIDER_CONTACT(i).getPRD();
           String prdRoleId=prd.getProviderRole(0).getIdentifier().getValue();

           logger.debug("prd role Id : "+prdRoleId);

           if (providerRoleId.equals(prdRoleId))
           {
           	return(prd);
           }
	}
	
	return(null);
}
 
Example 21
Project: OSCAR-ConCert   File: TDISHandler.java   View source code 6 votes vote down vote up
public String getHealthNum() {
	//int pat_ids = pat_25.getPID().getPatientIdentifierListReps();
	 String hin;
	try {
		String[] hinArray = null ;
		ca.uhn.hl7v2.model.v25.datatype.CX patIdList = pat_25.getPID().getPatientIdentifierList(0);
		String hnumber = patIdList.getIDNumber().getValue();
		if (hnumber != null)
			hinArray = hnumber.split("-");
			if ((hinArray!=null)&& hinArray.length>0) {
			hin = hinArray[0];
			return hin; } //return first instance that is not null
	} catch (HL7Exception e) {
		logger.error("ERROR getting the health number for HL7 lab report patient: " + e.toString());
	}

	return "";
}
 
Example 22
Project: OSCAR-ConCert   File: EpsilonHandler.java   View source code 6 votes vote down vote up
@Override
public void init(String hl7Body) throws HL7Exception {
	if (hl7Body.startsWith("MSH")) {
		int index = 0;
		for (int i = 0; i < 11; i++)
			index = hl7Body.indexOf('|', index + 1);
		int tmp = index + 1;
		String tmph = hl7Body.substring(0, tmp);
		index = hl7Body.indexOf('|', index + 1);
		if (hl7Body.substring(tmp, index).trim().length() == 0)
			hl7Body = tmph + "2.3" + hl7Body.substring(index);
	}
	Parser p = new PipeParser();
	p.setValidationContext(new NoValidation());
	msg = (ORU_R01) p.parse(hl7Body.replaceAll("\n", "\r\n"));
}
 
Example 23
Project: OSCAR-ConCert   File: IHAHandler.java   View source code 6 votes vote down vote up
private int getNTELocation(int i, int j) throws HL7Exception{
    int k = 0;
    int obrCount = 0;
    int obxCount = 0;
    String[] segments = terser.getFinder().getRoot().getNames();
    
    while (k != segments.length && obrCount != i+1){
        if (segments[k].substring(0, 3).equals("OBR"))
            obrCount++;
        k++;
    }
    
    Structure[] obxSegs;
    while (k != segments.length && obxCount != j+1){
        
        
        if (segments[k].substring(0, 3).equals(("OBX"))){
            obxSegs = terser.getFinder().getRoot().getAll(segments[k]);
            obxCount = obxCount + obxSegs.length;
        }
        k++;
    }
    
    return(k);
}
 
Example 24
Project: Camel   File: HL7ValidateTest.java   View source code 6 votes vote down vote up
@Test
public void testUnmarshalFailed() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:unmarshal");
    mock.expectedMessageCount(0);

    String body = createHL7AsString();
    try {
        template.sendBody("direct:unmarshalFailed", body);
        fail("Should have thrown exception");
    } catch (CamelExecutionException e) {
        assertIsInstanceOf(HL7Exception.class, e.getCause());
        assertIsInstanceOf(DataTypeException.class, e.getCause());
        assertTrue("Should be a validation error message", e.getCause().getMessage().startsWith("ca.uhn.hl7v2.validation.ValidationException: Validation failed:"));
    }

    assertMockEndpointsSatisfied();
}
 
Example 25
Project: HL7Receiver   File: HL7ExceptionHandler.java   View source code 5 votes vote down vote up
public String processException(String incomingMessage, Map<String, Object> incomingMetadata, String outgoingMessage, Exception exception) throws HL7Exception {
    try {
        UUID deadLetterUuid = UUID.randomUUID();
        LOG.error("Exception while processing message", constructLogbackDeadLetterArgs(deadLetterUuid, exception));

        dataLayer.logDeadLetter(
                configuration.getDbConfiguration().getInstanceId(),
                dbChannel.getChannelId(),
                connectionManager.getConnectionId(incomingMetadata),
                configuration.getMachineName(),
                dbChannel.getPortNumber(),
                HL7ConnectionManager.getRemoteHost(incomingMetadata),
                HL7ConnectionManager.getRemotePort(incomingMetadata),
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                incomingMessage,
                null,
                outgoingMessage,
                constructFormattedException(exception),
                deadLetterUuid,
                null);
    } catch (Exception e3) {
        LOG.error("Error logging dead letter", e3);
    }

    if (outgoingMessage == null)
        outgoingMessage = "";

    return outgoingMessage;
}
 
Example 26
Project: HL7Receiver   File: HL7MessageProcessor.java   View source code 5 votes vote down vote up
private void initialiseKeycloak() throws HL7Exception {

        if (!lastInitialisedKeycloak.plusHours(KEYCLOAK_REINITIALISATION_WINDOW_HOURS).isBefore(LocalDateTime.now()))
            return;

        final DbEds dbEds = configuration.getDbConfiguration().getDbEds();

        if (dbEds.isUseKeycloak()) {
            LOG.trace("Initialising keycloak at: {}", dbEds.getKeycloakTokenUri());

            try {
                KeycloakClient.init(dbEds.getKeycloakTokenUri(),
                        dbEds.getKeycloakRealm(),
                        dbEds.getKeycloakUsername(),
                        dbEds.getKeycloakPassword(),
                        dbEds.getKeycloakClientId());

                Header response = KeycloakClient.instance().getAuthorizationHeader();

                LOG.trace("Keycloak initialised");

            } catch (IOException e) {
                LOG.error("Error initialising keycloak", e);
                throw new HL7Exception("Error initialising keycloak", e);
            }

        } else {
            LOG.trace("Keycloak is not enabled");
        }

        lastInitialisedKeycloak = LocalDateTime.now();
    }
 
Example 27
Project: OSCAR-ConCert   File: ViewOruR01UIBean.java   View source code 5 votes vote down vote up
private String getProviderDisplayString(String actionRole) throws HL7Exception
{
	Provider provider=OruR01.getProviderByActionRole(oruR01, actionRole);
	
	StringBuilder sb = new StringBuilder();

	sb.append(provider.getLastName());
	sb.append(", ");
	sb.append(provider.getFirstName());

	if (provider.getProviderNo() != null) {
		sb.append(" (");
		sb.append(provider.getProviderNo());
		sb.append(')');
	}

	if (provider.getPhone() != null) {
		sb.append(", ");
		sb.append(provider.getPhone());
	}

	if (provider.getEmail() != null) {
		sb.append(", ");
		sb.append(provider.getEmail());
	}

	if (provider.getAddress() != null) {
		sb.append(", ");
		sb.append(provider.getAddress());
	}

	return (StringEscapeUtils.escapeHtml(sb.toString()));
}
 
Example 28
Project: OSCAR-ConCert   File: EaapsMessageSupport.java   View source code 5 votes vote down vote up
public void init(String hl7Body) throws HL7Exception, EncodingNotSupportedException {
	hl7Body = preProcess(hl7Body);
	Parser parser = new GenericParser();
	parser.setValidationContext(new NoValidation());
	Message m = parser.parse(hl7Body);
	if (!(m instanceof ORU_R01)) {
		throw new HL7Exception("Unsupported message type: " + m.getName() + ". Expected ORU^R01 ver 2.2");
	}
	ORU_R01 message = (ORU_R01) m;
	int commentReps = message.getPATIENT_RESULT().getORDER_OBSERVATION().currentReps("NTE");
	if (commentReps < 2) {
		throw new HL7Exception("Expected at least 2 comments in the NTE field.");
	}
	this.message = message;
}
 
Example 29
Project: OSCAR-ConCert   File: EaapsMessageSupport.java   View source code 5 votes vote down vote up
public String getProviderNote() {
	try {
		NTE nte = message.getPATIENT_RESULT().getORDER_OBSERVATION().getNTE(2);
		return decode(nte.getComment(0).getValue());
	} catch (HL7Exception e) {
		throw new IllegalStateException("Unable to get comment field from the message", e);
	}
}
 
Example 30
Project: OSCAR-ConCert   File: EaapsMessageSupport.java   View source code 5 votes vote down vote up
public String getRecommendations() {
	try {
		NTE nte = message.getPATIENT_RESULT().getORDER_OBSERVATION().getNTE(1);
		String commentValue = nte.getComment(0).getValue();
		return decode(commentValue);
	} catch (HL7Exception e) {
		throw new IllegalStateException("Unable to get comment field from the message", e);
	}
}
 
Example 31
Project: OSCAR-ConCert   File: OLISHL7Handler.java   View source code 5 votes vote down vote up
public HashMap<String, String> getReportingFacilityAddress() {
	try {
		String value;
		HashMap<String, String> address;
		String identifier = getString(terser.get("/.ZBR-5-7"));
		if ("".equals(identifier)) {
			return null;
		}
		address = new HashMap<String, String>();
		value = getString(terser.get("/.ZBR-5-1"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("Street Address", value);
		}
		value = getString(terser.get("/.ZBR-5-2"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("Other Designation", value);
		}
		value = getString(terser.get("/.ZBR-5-3"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("City", value);
		}
		value = getString(terser.get("/.ZBR-5-4"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("Province", value);
		}
		value = getString(terser.get("/.ZBR-5-5"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("Postal Code", value);
		}
		value = getString(terser.get("/.ZBR-5-6"));
		if (stringIsNotNullOrEmpty(value)) {
			address.put("Country", value);
		}
		address.put("Address Type", addressTypeNames.get(identifier));
		return address;
	} catch (HL7Exception e) {
		MiscUtils.getLogger().error("OLIS HL7 Error", e);
		return null;
	}
}
 
Example 32
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 5 votes vote down vote up
protected PatientId extractPatientAccountNumber() throws HL7Exception {
	PatientId id = null;

	String identifier = t.get("PID-18-1");
	String authority = t.get("PID-18-4");
	String typeId = t.get("PID-18-5");

	if(identifier == null)
		return null;

	id = new PatientId(identifier, authority, typeId);

	return id;
}
 
Example 33
Project: product-ei   File: HL7InboundTestSender.java   View source code 5 votes vote down vote up
public String send(String host, int port) throws HL7Exception, IOException, LLPException {
       HapiContext context = new DefaultHapiContext();
       Connection c = context.newClient(host, port, false);
       Initiator initiator = c.getInitiator();

       ADT_A01 msg = new ADT_A01();
       msg.initQuickstart("ADT", "A01", "T");
       Message resp = initiator.sendAndReceive(msg);
       return resp.encode();
}
 
Example 34
Project: OSCAR-ConCert   File: BasePhsStarHandler.java   View source code 5 votes vote down vote up
protected void extractAppointmentLocation() throws HL7Exception {
	String ruCode = t.get("AIL-3-1");
	String roomAbbr = t.get("AIL-3-2");
	String facilityCode = t.get("AIL-3-4");
	String descr = t.get("AIL-3-9");

	String locationType=t.get("AIL-4-1");
	String locationTypePool=t.get("AIL-4-2");

	String strStartTime = t.get("AIL-6-1");
	Date startTime = this.convertToDate(strStartTime);

	String offset = t.get("AIL-7-1");
	String offsetUnit = t.get("AIL-8-1");
	String duration = t.get("AIL-9-1");
	String durationUnit = t.get("AIL-10-1");
	String statusCode = t.get("AIL-12-1"); //BOOKED or CANCEL

	logger.debug("ruCode="+ruCode);
	logger.debug("roomAbbr="+roomAbbr);
	logger.debug("FacilityCode="+facilityCode);
	logger.debug("descr="+descr);
	logger.debug("locationType="+locationType);
	logger.debug("locationTypePool="+locationTypePool);
	logger.debug("startTime="+startTime);
	logger.debug("offset="+offset);
	logger.debug("offset unit="+offsetUnit);
	logger.debug("duration="+duration);
	logger.debug("duration unit="+durationUnit);
	logger.debug("statusCode="+statusCode);
}
 
Example 35
Project: product-ei   File: HL7InboundTestSender.java   View source code 5 votes vote down vote up
public String send(String host, int port, Message message) throws HL7Exception, IOException, LLPException {
    HapiContext context = new DefaultHapiContext();
    Connection c = context.newClient(host, port, false);
    Initiator initiator = c.getInitiator();

    Message resp = initiator.sendAndReceive(message);
    return resp.encode();
}
 
Example 36
Project: OSCAR-ConCert   File: OLISHL7Handler.java   View source code 5 votes vote down vote up
public String getAdmittingProviderName() {
	try {
		return getFullDocName("/.PV1-17-");
	} catch (HL7Exception e) {
		MiscUtils.getLogger().error("OLIS HL7 Error", e);
		return "";
	}
}
 
Example 37
Project: OSCAR-ConCert   File: PhsStarHandler.java   View source code 5 votes vote down vote up
public void updateAppointmentAccountNumber() throws HL7Exception {
	OtherId otherId = null;
	PatientId id = getTemporaryAccountNumber();
	Map<String,PatientId> ids = this.extractInternalPatientIds();

	if(id != null) {
		otherId = OtherIdManager.searchTable(OtherIdManager.APPOINTMENT,"TAN",id.getId());
	} else {
		//find appt by TAN or AN
		if(ids.get("TAN")!=null) {
			otherId = OtherIdManager.searchTable(OtherIdManager.APPOINTMENT,"TAN",ids.get("TAN").getId());
		}
		if(ids.get("AN")!=null) {
			otherId = OtherIdManager.searchTable(OtherIdManager.APPOINTMENT,"AN",ids.get("AN").getId());
		}
		if(otherId==null && extractPatientAccountNumber() != null) {
			otherId = OtherIdManager.searchTable(OtherIdManager.APPOINTMENT,"AN",extractPatientAccountNumber().getId());
		}
	}

	if(otherId == null) {
		logger.warn("Could not find appt to reschedule");
		return;
	}

	Appointment appt = appointmentDao.find(Integer.parseInt(otherId.getTableId()));

	if(appt == null) {
		logger.warn("couldn't load up the appt");
		return;
	}
	if(getAccountNumber() != null) {
		OtherIdManager.saveIdAppointment(appt.getId(), "AN", getAccountNumber().getId());
	}
	if(ids.get("AN")!=null) {
		OtherIdManager.saveIdAppointment(appt.getId(), "AN", getAccountNumber().getId());
	}
}
 
Example 38
Project: OSCAR-ConCert   File: HL7A04Data.java   View source code 5 votes vote down vote up
/**
 * 
 */
   public boolean save() throws HL7Exception {
	if (this.message == null)
		this.generateA04MessageGuelph();
	       
       logger.info("Creating HL7 A04 file with contents: " + this.message);
       
       String saveDir = oscarProperties.getHL7A04BuildDirectory();
       
       // create HL7 A04 file
       try {
       	File directory = new File(saveDir);
       	if (!directory.exists())
       		directory.mkdir();
       	
       	FileWriter fw = new FileWriter(saveDir + this.fileName, true);
       	BufferedWriter out = new BufferedWriter(fw);
       	out.write(this.message);
       	out.close();
       } catch (IOException e) {
		logger.error("ERROR while saving HL7 A04 file: " + e.toString());
		return false;
       }
       
       logger.info("Successfully saved HL7 A04 file: " + saveDir + this.fileName);
       
       return true;
}
 
Example 39
Project: OSCAR-ConCert   File: OLISHL7Handler.java   View source code 5 votes vote down vote up
@Override
public String getLastName() {
	try {
		return (getString(terser.get("/.PID-5-1")));
	} catch (HL7Exception ex) {
		return ("");
	}
}
 
Example 40
Project: Camel   File: ValidationContextPredicate.java   View source code 5 votes vote down vote up
@Override
public boolean matches(Exchange exchange) {
    try {
        Message message = exchange.getIn().getBody(Message.class);
        ValidationContext context = validatorExpression != null
                ? validatorExpression.evaluate(exchange, ValidationContext.class)
                : dynamicValidationContext(message, exchange.getIn().getHeader(HL7Constants.HL7_CONTEXT, HapiContext.class));
        MessageValidator validator = new MessageValidator(context, false);
        return validator.validate(message);
    } catch (HL7Exception e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    }
}