@Test
  public void testSendMessageSimpleXml() throws Exception {

    String message = // -
        "MSH|^~\\&|||||200803051508||ADT^A31|2|P|2.5\r"
            + // -
            "EVN||200803051509\r"
            + // -
            "PID|||ZZZZZZ83M64Z148R^^^SSN^SSN^^20070103\r"; // -
    message =
        new DefaultXMLParser().encode(PipeParser.getInstanceWithNoValidation().parse(message));

    HohRawClientSimple client = new HohRawClientSimple("localhost", myPort, "/theUri");
    client.setAuthorizationCallback(new SingleCredentialClientCallback("hello", "hapiworld"));
    IReceivable<String> response = client.sendAndReceive(new RawSendable(message));

    ourLog.info("Received response");

    assertEquals(message, myServerSocketThread.getMessage());
    String responseMessage = response.getMessage();
    assertTrue(responseMessage, responseMessage.contains("<MSH>"));
    assertEquals(myServerSocketThread.getReply().encode(), responseMessage);

    assertEquals(EncodingStyle.XML.getContentType(), myServerSocketThread.getContentType());
    assertEquals(EncodingStyle.XML, myServerSocketThread.getEncoding());
  }
  @Test
  public void testTerserGetPrimitive_VariesCompositeFirstComponent() throws HL7Exception {
    final Varies variesField = new Varies(mshOnly);
    final Primitive comp1Sub1 = Terser.getPrimitive(variesField, 1, 1);
    comp1Sub1.setValue("comp1Sub1");
    final Primitive comp1Sub2 = Terser.getPrimitive(variesField, 1, 2);
    comp1Sub2.setValue("comp1Sub2");
    final Primitive comp2Sub1 = Terser.getPrimitive(variesField, 2, 1);
    comp2Sub1.setValue("comp2Sub1");

    assertEquals(GenericComposite.class, variesField.getData().getClass());

    final GenericComposite field = (GenericComposite) variesField.getData();
    final Type typeComp1 = field.getComponent(0);
    assertEquals(typeComp1.getClass(), Varies.class);

    final Varies variesComp1 = (Varies) typeComp1;
    assertEquals(GenericComposite.class, variesComp1.getData().getClass());

    final GenericComposite comp1 = (GenericComposite) variesComp1.getData();
    final Type typeSub1 = comp1.getComponent(1);
    assertEquals(typeSub1.getClass(), Varies.class);

    final Varies variesSub1 = (Varies) typeSub1;
    assertEquals(GenericPrimitive.class, variesSub1.getData().getClass());

    assertEquals("comp1Sub1&comp1Sub2^comp2Sub1", PipeParser.encode(variesField, encoders));
  }
 /**
  * Returns the datatype and attempts to pipe-encode it. For example, a string implementation might
  * return "ST[Value^Value2]". This is only intended for logging/debugging purposes.
  */
 static String toString(Type theType) {
   StringBuilder b = new StringBuilder();
   b.append(theType.getClass().getSimpleName());
   b.append("[");
   b.append(PipeParser.encode(theType, EncodingCharacters.defaultInstance()));
   b.append("]");
   return b.toString();
 }
  protected List<ValidationException> testField(
      Type type, SegmentType.Field profile, boolean escape) {
    List<ValidationException> exList = new ArrayList<>();

    UsageInfo usage = new UsageInfo(profile);

    // account for MSH 1 & 2 which aren't escaped
    String encoded = null;
    if (!escape && Primitive.class.isAssignableFrom(type.getClass()))
      encoded = ((Primitive) type).getValue();

    exList.addAll(testType(type, profile.getDatatype(), usage, encoded, false));

    // test children
    if (validateChildren) {
      if (profile.getComponents().size() > 0 && !usage.disallowed()) {
        if (Composite.class.isAssignableFrom(type.getClass())) {
          Composite comp = (Composite) type;
          int i = 1;
          boolean nullContext = false;
          for (SegmentType.Field.Component component : profile.getComponents()) {
            try {
              SegmentType.Field.Component component2;
              if (nullContext) {
                component2 = new SegmentType.Field.Component();
                try {
                  BeanUtils.copyProperties(component2, component);
                } catch (InvocationTargetException | IllegalAccessException e) {
                  // nop
                }
                component2.setUsage("NULL");
              } else {
                component2 = component;
                if ((i == 1)
                    && profile.isNullable()
                    && PipeParser.encode(comp.getComponent(0), this.enc).equals("\"\"")) {
                  nullContext = true;
                }
              }

              exList.addAll(testComponent(comp.getComponent(i - 1), component2));
            } catch (DataTypeException de) {
              profileNotHL7Compliant(exList, COMPONENT_TYPE_MISMATCH, type.getName(), i);
            }
            ++i;
          }
          exList.addAll(checkUndefinedComponents(comp, profile.getComponents().size()));
        } else {
          profileNotHL7Compliant(exList, WRONG_FIELD_TYPE, type.getClass().getName());
        }
      }
    }
    return exList;
  }
  public static void main(String[] args) throws HL7Exception, JAXBException {

    String msg =
        "MSH|^~\\&|1.3.6.1.4.1.12201^1.3.6.1.4.1.12201.101.1|UHN^1.3.6.1.4.1.12201|ConnectingGTA|ConnectingGTA|20130225000100-0500|2954864636aaa|ADT^A11^ADT_A09|142981|T|2.5|||NE|AL|CAN|8859/1|||CGTA_CDR_INPUT_2_0\r"
            + "EVN||201302250001\r"
            + "PID|1||7013623^^^1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.101.1^MR~HN3651^^^1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.101.1^PI||Test^Alexfive^^^^^L||19700105|M|||21 jump street^^NORTH YORK^CANON^M3A 1Y8^Can^H||(416)444-4444^PRN^PH^^1^416^4444444||eng^English^HL70296|||||||||||||||N\r"
            + "PV1|1|I|^^^1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.100.1|R||^^^1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.100.1||1185^Abrams^Howard^^^Dr.^MD^^1.3.6.1.4.1.12201.1.2.1.5&1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.101.1||General Internal Medicine||||||N|13546^Generic^Physician^Moe^^Dr.^MD^^1.3.6.1.4.1.12201.1.2.1.5&1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.101.1||11210000302^^^1.3.6.1.4.1.12201&1.3.6.1.4.1.12201.101.1^VN|||||||||||||||||||||||||20120628105900-0400\r"
            + "PV2|||^test";
    Message parsed = PipeParser.getInstanceWithNoValidation().parse(msg);
    CgtaHohServlet s = new CgtaHohServlet();
    MyApplication application = s.new MyApplication();
    application.processMessage(parsed, new HashMap<String, Object>());
  }
  @Test
  public void testParser_VariesCompositeSecondField() throws HL7Exception {
    final Varies variesField = new Varies(mshOnly);
    final Parser parser = mshOnly.getParser();
    final String hl7Text = "^A3456&2Rozwick&don&FURTHER&JR&MR&DR^200701010933^200702031022";
    parser.parse(variesField, hl7Text, encoders);
    final Composite data = (Composite) variesField.getData();
    assertEquals(4, data.getComponents().length);

    final Varies component = (Varies) data.getComponent(1);
    assertEquals(GenericComposite.class, component.getData().getClass());
    assertEquals(7, ((Composite) component.getData()).getComponents().length);
    assertEquals(hl7Text, PipeParser.encode(variesField, encoders));
  }
  /**
   * Tests a Type against the corresponding section of a profile.
   *
   * @param encoded optional encoded form of type (if you want to specify this -- if null, default
   *     pipe-encoded form is used to check length and constant val)
   */
  protected List<ValidationException> testType(
      Type type, String dataType, UsageInfo usage, String encoded, boolean testUsage) {
    ArrayList<ValidationException> exList = new ArrayList<>();
    if (encoded == null) encoded = PipeParser.encode(type, this.enc);

    if (testUsage) {
      testUsage(exList, encoded, usage);
    }

    if (!usage.disallowed() && !encoded.isEmpty()) {
      // check datatype
      if ((type instanceof ca.uhn.hl7v2.model.v231.datatype.TSComponentOne
              || type instanceof ca.uhn.hl7v2.model.v24.datatype.TSComponentOne)
          && !dataType.equals("ST")) {
        profileNotHL7Compliant(exList, HL7_DATATYPE_MISMATCH, type.getName(), dataType);
      } else if (!(type instanceof TSComponentOne) && !type.getName().contains(dataType)) {
        profileViolatedWhen(
            !(type.getClass().getSimpleName().equals("Varies")
                || type.getClass().getSimpleName().equals("QIP")),
            exList,
            HL7_DATATYPE_MISMATCH,
            type.getName(),
            dataType);
      }

      // check length
      profileViolatedWhen(
          encoded.length() > usage.length,
          exList,
          LENGTH_EXCEEDED,
          usage.name,
          encoded.length(),
          usage.length);

      // check constant value
      if (usage.constantValue != null && usage.constantValue.length() > 0) {
        profileViolatedWhen(
            !encoded.equals(usage.constantValue),
            exList,
            WRONG_CONSTANT_VALUE,
            encoded,
            usage.constantValue);
      }

      // TODO : check against table, or do we need this check?
      // Gazelle checks code system and issues a WARNING if a check fails
    }

    return exList;
  }
 private Message getTestMessage() throws Exception {
   String message =
       "MSH|^~\\&|Fake Sending App|Fake Sending Facility||Fake Receiving Facility|200108151718||ACK^A01^ACK|20|P|2.4|||||||||TestProfile|\rMSA|AA\r";
   PipeParser p = new PipeParser();
   return p.parse(message);
 }