private boolean uploadToBORN(byte[] xmlFile, String filename) {
    String documentDir = oscarProperties.getProperty("DOCUMENT_DIR");

    boolean success = false;
    if (documentDir != null && new File(documentDir).exists()) {
      FileOutputStream fos = null;
      try {
        File f = new File(documentDir + File.separator + filename);
        fos = new FileOutputStream(f);
        fos.write(xmlFile);

        success = BornFtpManager.upload18MEWBVDataToRepository(xmlFile, filename);
      } catch (IOException e) {
        logger.warn("Unabled to backup file to document dir", e);
      } finally {
        try {
          if (fos != null) fos.close();
        } catch (IOException e) {
          logger.warn("Fail to close file output stream", e);
        }
      }
    } else {
      logger.warn("Cannot find DOCUMENT_DIR");
    }
    return success;
  }
 public List<Program> getPrograms(Integer facilityId) {
   if (OscarProperties.getInstance().getBooleanProperty("FILTER_ON_FACILITY", "true")) {
     return programDao.getProgramsByFacilityId(facilityId);
   } else {
     return programDao.getAllPrograms();
   }
 }
Exemple #3
0
  // write OHIP file to it
  public void writeFile(String value1) {
    try {
      String home_dir;
      home_dir = OscarProperties.getInstance().getProperty("HOME_DIR");
      FileOutputStream out = new FileOutputStream(home_dir + ohipFilename);
      PrintStream p = new PrintStream(out);
      p.println(value1);

      p.close();
      out.close();
    } catch (Exception e) {
      logger.error("Write OHIP File Error", e);
    }
  }
Exemple #4
0
  // get path from the property file, e.g.
  // OscarDocument/.../billing/download/, and then write to it
  public void writeHtml(String htmlvalue1) {
    try {
      String home_dir1;
      home_dir1 = OscarProperties.getInstance().getProperty("HOME_DIR");

      FileOutputStream out1 = new FileOutputStream(home_dir1 + htmlFilename);
      PrintStream p1 = new PrintStream(out1);
      p1.println(htmlvalue1);

      p1.close();
      out1.close();
    } catch (Exception e) {
      logger.error("Write HTML File Error!!!", e);
    }
  }
Exemple #5
0
  public ActionForward edit(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    String id = request.getParameter("episode.id");

    if (id != null) {
      Episode e = episodeDao.find(Integer.valueOf(id));
      request.setAttribute("episode", e);
    }

    String[] codingSystems =
        OscarProperties.getInstance().getProperty("dxResearch_coding_sys", "").split(",");
    List<String> cs = Arrays.asList(codingSystems);
    request.setAttribute("codingSystems", cs);
    request.setAttribute("demographicNo", request.getParameter("demographicNo"));
    return mapping.findForward("form");
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    if (!securityInfoManager.hasPrivilege(
        LoggedInInfo.getLoggedInInfoFromSession(request), "_con", "r", null)) {
      throw new SecurityException("missing required security object (_con)");
    }

    String reqId = request.getParameter("reqId");
    String demoNo = request.getParameter("demographicNo");
    // ArrayList docs = EDocUtil.listDocs( demoNo, reqId, EDocUtil.ATTACHED);
    String[] docs = request.getParameterValues("docNo");
    ArrayList alist = new ArrayList();
    String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

    for (int i = 0; i < docs.length; i++) alist.add(path + docs[i]);

    if (alist.size() > 0) {
      response.setContentType("application/pdf"); // octet-stream
      response.setHeader(
          "Content-Disposition",
          "attachment; filename=\"combinedPDF-"
              + UtilDateUtilities.getToday("yyyy-mm-dd.hh.mm.ss")
              + ".pdf\"");
      try {
        ConcatPDF.concat(alist, response.getOutputStream());
      } catch (IOException ex) {
        MiscUtils.getLogger().error("Error", ex);
      }
      return null;
    }

    return mapping.findForward("noprint");
  }
Exemple #7
0
  @Override
  public String parse(String serviceName, String fileName, int fileId, String ipAddr) {

    String providerNo = "-1";
    String filePath = fileName;
    if (!(fileName.endsWith(".pdf") || fileName.endsWith(".PDF"))) {
      logger.error("Document " + fileName + "does not have pdf extension");
      return null;
    } else {
      int fileNameIdx = fileName.lastIndexOf("/");
      fileName = fileName.substring(fileNameIdx + 1);
    }

    EDoc newDoc =
        new EDoc(
            "",
            "",
            fileName,
            "",
            providerNo,
            providerNo,
            "",
            'A',
            oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"),
            "",
            "",
            "demographic",
            "-1",
            false);

    newDoc.setDocPublic("0");

    InputStream fis = null;

    try {
      fis = new FileInputStream(filePath);
      newDoc.setContentType("application/pdf");

      // Find the number of pages
      PdfReader reader = new PdfReader(filePath);
      int numPages = reader.getNumberOfPages();
      reader.close();
      newDoc.setNumberOfPages(numPages);

      String doc_no = EDocUtil.addDocumentSQL(newDoc);

      LogAction.addLog(
          providerNo, LogConst.ADD, LogConst.CON_DOCUMENT, doc_no, ipAddr, "", "DocUpload");

      // Get provider to route document to
      String batchPDFProviderNo =
          OscarProperties.getInstance().getProperty("batch_pdf_provider_no");
      if ((batchPDFProviderNo != null) && !batchPDFProviderNo.isEmpty()) {

        ProviderInboxRoutingDao providerInboxRoutingDao =
            (ProviderInboxRoutingDao) SpringUtils.getBean("providerInboxRoutingDAO");
        providerInboxRoutingDao.addToProviderInbox(
            batchPDFProviderNo, Integer.parseInt(doc_no), "DOC");

        // Add to default queue for now, not sure how or if any other queues can be used anyway
        // (MAB)
        QueueDocumentLinkDao queueDocumentLinkDAO =
            (QueueDocumentLinkDao) SpringUtils.getBean("queueDocumentLinkDAO");
        Integer did = Integer.parseInt(doc_no.trim());
        queueDocumentLinkDAO.addToQueueDocumentLink(1, did);
      }
    } catch (FileNotFoundException e) {
      logger.info("An unexpected error has occurred:" + e.toString());
      return null;
    } catch (Exception e) {
      logger.info("An unexpected error has occurred:" + e.toString());
      return null;
    } finally {
      try {
        if (fis != null) {
          fis.close();
        }
      } catch (IOException e1) {
        logger.info("An unexpected error has occurred:" + e1.toString());
        return null;
      }
    }

    return "success";
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException {
    if (request.getSession().getAttribute("user") == null) {
      return (mapping.findForward("Logout"));
    }

    BillingReProcessBillForm frm = (BillingReProcessBillForm) form;

    GregorianCalendar now = new GregorianCalendar();
    int curYear = now.get(Calendar.YEAR);
    int curMonth = (now.get(Calendar.MONTH) + 1);
    int curDay = now.get(Calendar.DAY_OF_MONTH);
    String curDate =
        String.valueOf(curYear) + "-" + String.valueOf(curMonth) + "-" + String.valueOf(curDay);

    String dataCenterId = OscarProperties.getInstance().getProperty("dataCenterId");

    String billingmasterNo = frm.getBillingmasterNo();

    String demographicNo = frm.getDemoNo();
    DemographicData demoD = new DemographicData();
    org.oscarehr.common.model.Demographic demo =
        demoD.getDemographic(LoggedInInfo.getLoggedInInfoFromSession(request), demographicNo);

    oscar.oscarBilling.data.BillingFormData billform =
        new oscar.oscarBilling.data.BillingFormData();

    ///
    String providerNo = frm.getProviderNo(); // f
    String demographicFirstName = demo.getFirstName(); // d
    String demographicLastName = demo.getLastName(); // d
    String name_verify =
        demographicFirstName.substring(0, 1) + " " + demographicLastName.substring(0, 2); // d
    String billingGroupNo = billform.getGroupNo(providerNo);
    String practitionerNo = billform.getPracNo(providerNo); // p
    String hcNo = demo.getHin().trim() + demo.getVer().trim(); // d
    String dependentNo = frm.getDependentNo(); // f

    String visitLocation = frm.getLocationVisit(); // f
    String clarificationCode = visitLocation.substring(0, 2); // f
    String anatomicalArea = frm.getAnatomicalArea(); // f
    String afterHour = frm.getAfterHours(); // f
    String newProgram = frm.getNewProgram(); // f
    String billingUnit = frm.getBillingUnit(); // /f
    String billingServiceCode = frm.getService_code(); // f
    String billingServicePrice = frm.getBillingAmount(); // f
    String payment_mode = frm.getPaymentMode(); // f
    String serviceDate = frm.getServiceDate(); // f
    String serviceToDate = frm.getServiceToDay(); // f
    String submissionCode = frm.getSubmissionCode(); // f
    String exSubmissionCode = ""; // f
    String dxCode1 = frm.getDx1(); // f
    String dxCode2 = frm.getDx2(); // f
    String dxCode3 = frm.getDx3(); // f
    String dxExpansion = ""; // f
    String serviceLocation = frm.getServiceLocation().substring(0, 1); // f

    String referralFlag1 = frm.getReferalPracCD1(); // f
    String referralNo1 = frm.getReferalPrac1(); // f
    String referralFlag2 = frm.getReferalPracCD2(); // f
    String referralNo2 = frm.getReferalPrac2(); // f
    String timeCall = frm.getTimeCallRec(); // f
    String serviceStartTime = frm.getStartTime(); // f
    String serviceEndTime = frm.getFinishTime(); // f
    String birthDate = DemographicData.getDob(demo); // d
    String correspondenceCode = frm.getCorrespondenceCode(); // f
    String claimComment = frm.getShortComment(); // f

    String billingStatus = frm.getStatus(); // f

    String oinInsurerCode = frm.getInsurerCode(); // f
    String oinRegistrationNo = demo.getHin() + demo.getVer(); // d
    String oinBirthdate = DemographicData.getDob(demo); // d
    String oinFirstName = demo.getFirstName(); // d
    String oinSecondName = ""; // d
    String oinSurname = demo.getLastName(); // d
    String oinSexCode = demo.getSex(); // d
    String oinAddress = demo.getAddress(); // d
    String oinAddress2 = demo.getCity(); // d
    String oinAddress3 = ""; // d
    String oinAddress4 = ""; // d
    String oinPostalcode = demo.getPostal(); // d

    String hcType = demo.getHcType(); // d
    String billRegion = OscarProperties.getInstance().getProperty("billregion");
    ////

    String submit = frm.getSubmit();
    String secondSQL = null;

    if (submit.equals("Resubmit Bill") || billingStatus.equals("O")) {
      billingStatus = "O";
      secondSQL = "update billing set status = 'O' where billing_no ='" + frm.getBillNumber() + "'";
    } else if (submit.equals("Settle Bill")) {
      billingStatus = "S";
    }

    if (hcType.equals(billRegion)) { // if its bc go on
      oinInsurerCode = "";
      oinRegistrationNo = "";
      oinBirthdate = "";
      oinFirstName = "";
      oinSecondName = "";
      oinSurname = "";
      oinSexCode = "";
      oinAddress = "";
      oinAddress2 = "";
      oinAddress3 = "";
      oinAddress4 = "";
      oinPostalcode = "";

    } else { // other provinces
      oinInsurerCode = hcType;
      hcNo = "000000000";
      name_verify = "0000";
    }

    Billingmaster b = billingmasterDao.getBillingmaster(Integer.parseInt(billingmasterNo));
    if (b != null) {
      b.setBillingstatus(billingStatus);
      b.setDatacenter(dataCenterId);
      b.setPayeeNo(billingGroupNo);
      b.setPractitionerNo(practitionerNo);
      b.setPhn(hcNo);
      b.setNameVerify(name_verify);
      b.setDependentNum(dependentNo);
      b.setBillingUnit(billingUnit);
      b.setClarificationCode(clarificationCode);
      b.setAnatomicalArea(anatomicalArea);
      b.setAfterHour(afterHour);
      b.setNewProgram(newProgram);
      b.setBillingCode(billingServiceCode);
      b.setBillAmount(billingServicePrice);
      b.setPaymentMode(payment_mode);
      b.setServiceDate(serviceDate);
      b.setServiceToDay(convertDate8Char(serviceDate));
      b.setSubmissionCode(exSubmissionCode);
      b.setExtendedSubmissionCode(exSubmissionCode);
      b.setDxCode1(dxCode1);
      b.setDxCode2(dxCode2);
      b.setDxCode3(dxCode3);
      b.setDxExpansion(dxExpansion);
      b.setServiceLocation(serviceLocation);
      b.setReferralFlag1(referralFlag1);
      b.setReferralNo1(referralNo1);
      b.setReferralFlag2(referralFlag2);
      b.setReferralNo2(referralNo2);
      b.setTimeCall(timeCall);
      b.setServiceStartTime(serviceStartTime);
      b.setServiceEndTime(serviceEndTime);
      b.setBirthDate(oinBirthdate);
      b.setCorrespondenceCode(correspondenceCode);
      b.setClaimComment(claimComment);
      b.setOinInsurerCode(oinInsurerCode);
      b.setOinRegistrationNo(oinRegistrationNo);
      b.setOinBirthdate(oinBirthdate);
      b.setOinFirstName(oinFirstName);
      b.setOinSecondName(oinSecondName);
      b.setOinSurname(oinSurname);
      b.setOinSexCode(oinSexCode);
      b.setOinAddress(oinAddress4);
      b.setOinAddress2(oinAddress2);
      b.setOinAddress3(oinAddress3);
      b.setOinAddress4(oinAddress4);
      b.setOinPostalcode(oinPostalcode);

      billingmasterDao.update(b);
    }

    if (secondSQL != null) {
      Billing bb = billingDao.find(Integer.parseInt(frm.getBillNumber()));
      if (bb != null) {
        bb.setStatus("O");
        billingDao.merge(bb);
      }
    }

    request.setAttribute("billing_no", billingmasterNo);
    return (mapping.findForward("success"));
  }
  public void updateBorn() {
    String rourkeFormName =
        oscarProperties.getProperty("born18m_eform_rourke", "Rourke Baby Record");
    String nddsFormName =
        oscarProperties.getProperty(
            "born18m_eform_ndds", "Nipissing District Developmental Screen");
    String rpt18mFormName =
        oscarProperties.getProperty(
            "born18m_eform_report18m", "Summary Report: 18-month Well Baby Visit");

    EForm rourkeForm = eformDao.findByName(rourkeFormName);
    EForm nddsForm = eformDao.findByName(nddsFormName);
    EForm rpt18mForm = eformDao.findByName(rpt18mFormName);

    List<Integer> rourkeFormDemoList = new ArrayList<Integer>();
    List<Integer> nddsFormDemoList = new ArrayList<Integer>();
    List<Integer> rpt18mFormDemoList = new ArrayList<Integer>();

    if (rourkeForm == null) logger.error(rourkeFormName + " form not found!");
    else buildDemoNos(rourkeForm, rourkeFormDemoList);
    if (nddsForm == null) logger.error(nddsFormName + " form not found!");
    else buildDemoNos(nddsForm, nddsFormDemoList);
    if (rpt18mForm == null) logger.error(rpt18mFormName + " form not found!");
    else buildDemoNos(rpt18mForm, rpt18mFormDemoList);

    HashMap<Integer, Integer> rourkeFormDemoFdids = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> nddsFormDemoFdids = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> rpt18mFormDemoFdids = new HashMap<Integer, Integer>();

    for (Integer demoNo : rourkeFormDemoList) {
      Integer fdid = checkRourkeDone(rourkeFormName, demoNo);
      if (fdid != null) rourkeFormDemoFdids.put(demoNo, fdid);
    }
    for (Integer demoNo : nddsFormDemoList) {
      Integer fdid = checkNddsDone(nddsFormName, demoNo);
      if (fdid != null) nddsFormDemoFdids.put(demoNo, fdid);
    }
    for (Integer demoNo : rpt18mFormDemoList) {
      Integer fdid = checkReport18mDone(rpt18mFormName, demoNo);
      if (fdid != null) rpt18mFormDemoFdids.put(demoNo, fdid);
    }

    // Upload to BORN repository
    for (Integer demoNo : rourkeFormDemoFdids.keySet()) {
      uploadToBorn(
          demoNo,
          rourkeFormDemoFdids.get(demoNo),
          nddsFormDemoFdids.get(demoNo),
          rpt18mFormDemoFdids.get(demoNo));
      nddsFormDemoFdids.remove(demoNo);
      rpt18mFormDemoFdids.remove(demoNo);
    }
    for (Integer demoNo : nddsFormDemoFdids.keySet()) {
      uploadToBorn(demoNo, null, nddsFormDemoFdids.get(demoNo), rpt18mFormDemoFdids.get(demoNo));
      rpt18mFormDemoFdids.remove(demoNo);
    }
    for (Integer demoNo : rpt18mFormDemoFdids.keySet()) {
      if (hasFormUploaded(rourkeFormName, demoNo) && hasFormUploaded(nddsFormName, demoNo)) {
        uploadToBorn(demoNo, null, null, rpt18mFormDemoFdids.get(demoNo));
      }
    }
  }
public class BORN18MConnector {
  private final String UPLOADED_TO_BORN = "uploaded_to_BORN";
  private final String VALUE_YES = "Yes";

  private final BornTransmissionLogDao logDao = SpringUtils.getBean(BornTransmissionLogDao.class);
  private final DemographicDao demographicDao = SpringUtils.getBean(DemographicDao.class);
  private final EFormDao eformDao = SpringUtils.getBean(EFormDao.class);
  private final EFormDataDao eformDataDao = SpringUtils.getBean(EFormDataDao.class);
  private final EFormValueDao eformValueDao = SpringUtils.getBean(EFormValueDao.class);
  private final Logger logger = MiscUtils.getLogger();

  private final OscarProperties oscarProperties = OscarProperties.getInstance();
  private final String filenameStart =
      "BORN_"
          + oscarProperties.getProperty("born18m_orgcode", "")
          + "_18MEWBV_"
          + oscarProperties.getProperty("born18m_env", "T");

  public void updateBorn() {
    String rourkeFormName =
        oscarProperties.getProperty("born18m_eform_rourke", "Rourke Baby Record");
    String nddsFormName =
        oscarProperties.getProperty(
            "born18m_eform_ndds", "Nipissing District Developmental Screen");
    String rpt18mFormName =
        oscarProperties.getProperty(
            "born18m_eform_report18m", "Summary Report: 18-month Well Baby Visit");

    EForm rourkeForm = eformDao.findByName(rourkeFormName);
    EForm nddsForm = eformDao.findByName(nddsFormName);
    EForm rpt18mForm = eformDao.findByName(rpt18mFormName);

    List<Integer> rourkeFormDemoList = new ArrayList<Integer>();
    List<Integer> nddsFormDemoList = new ArrayList<Integer>();
    List<Integer> rpt18mFormDemoList = new ArrayList<Integer>();

    if (rourkeForm == null) logger.error(rourkeFormName + " form not found!");
    else buildDemoNos(rourkeForm, rourkeFormDemoList);
    if (nddsForm == null) logger.error(nddsFormName + " form not found!");
    else buildDemoNos(nddsForm, nddsFormDemoList);
    if (rpt18mForm == null) logger.error(rpt18mFormName + " form not found!");
    else buildDemoNos(rpt18mForm, rpt18mFormDemoList);

    HashMap<Integer, Integer> rourkeFormDemoFdids = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> nddsFormDemoFdids = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> rpt18mFormDemoFdids = new HashMap<Integer, Integer>();

    for (Integer demoNo : rourkeFormDemoList) {
      Integer fdid = checkRourkeDone(rourkeFormName, demoNo);
      if (fdid != null) rourkeFormDemoFdids.put(demoNo, fdid);
    }
    for (Integer demoNo : nddsFormDemoList) {
      Integer fdid = checkNddsDone(nddsFormName, demoNo);
      if (fdid != null) nddsFormDemoFdids.put(demoNo, fdid);
    }
    for (Integer demoNo : rpt18mFormDemoList) {
      Integer fdid = checkReport18mDone(rpt18mFormName, demoNo);
      if (fdid != null) rpt18mFormDemoFdids.put(demoNo, fdid);
    }

    // Upload to BORN repository
    for (Integer demoNo : rourkeFormDemoFdids.keySet()) {
      uploadToBorn(
          demoNo,
          rourkeFormDemoFdids.get(demoNo),
          nddsFormDemoFdids.get(demoNo),
          rpt18mFormDemoFdids.get(demoNo));
      nddsFormDemoFdids.remove(demoNo);
      rpt18mFormDemoFdids.remove(demoNo);
    }
    for (Integer demoNo : nddsFormDemoFdids.keySet()) {
      uploadToBorn(demoNo, null, nddsFormDemoFdids.get(demoNo), rpt18mFormDemoFdids.get(demoNo));
      rpt18mFormDemoFdids.remove(demoNo);
    }
    for (Integer demoNo : rpt18mFormDemoFdids.keySet()) {
      if (hasFormUploaded(rourkeFormName, demoNo) && hasFormUploaded(nddsFormName, demoNo)) {
        uploadToBorn(demoNo, null, null, rpt18mFormDemoFdids.get(demoNo));
      }
    }
  }

  private void uploadToBorn(
      Integer demographicNo, Integer rourkeFdid, Integer nddsFdid, Integer report18mFdid) {
    byte[] born18mXml = generateXml(demographicNo, rourkeFdid, nddsFdid, report18mFdid);
    if (born18mXml == null) return;

    BornTransmissionLog log = prepareLog();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String dt = sdf.format(new Date());
    String filename = filenameStart + "_" + dt + "_" + getFileSuffix(log.getId()) + ".xml";

    boolean uploadOk = uploadToBORN(born18mXml, filename);
    if (uploadOk) recordFormSent(demographicNo, rourkeFdid, nddsFdid, report18mFdid);

    // update log filename and status (success=true/false)
    log.setFilename(filename);
    log.setSuccess(uploadOk);
    logDao.merge(log);

    logger.info("Uploaded [" + filename + "]");
    return;
  }

  private void buildDemoNos(EForm eform, List<Integer> demoList) {
    List<EFormData> eformDataList = eformDataDao.findByFormId(eform.getId());
    for (EFormData eformData : eformDataList) {
      if (!demoList.contains(eformData.getDemographicId()))
        demoList.add(eformData.getDemographicId());
    }
  }

  private Integer checkRourkeDone(String rourkeFormName, Integer demographicNo) {
    Integer fdid = getMaxFdid(rourkeFormName, demographicNo);
    if (fdid == null) return null; // no un-uploaded form data

    EFormValue eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "visit_date_18m");
    if (eformValue == null) return null;

    Date visitDate = UtilDateUtilities.StringToDate(eformValue.getVarValue(), "yyyy-MM-dd");
    if (!checkDate18m(visitDate, demographicNo)) return null;

    eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "subject");
    if (eformValue == null) return null;

    if (eformValue.getVarValue() != null
        && eformValue.getVarValue().toLowerCase().contains("draft")) {
      return null;
    }

    // check if the form is for 2-3y or 4-5y visit -> not uploading
    eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "visit_date_2y");
    if (eformValue != null
        && eformValue.getVarValue() != null
        && !eformValue.getVarValue().trim().isEmpty()) {
      return null;
    }

    eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "visit_date_4y");
    if (eformValue != null
        && eformValue.getVarValue() != null
        && !eformValue.getVarValue().trim().isEmpty()) {
      return null;
    }

    return fdid;
  }

  private Integer checkNddsDone(String nddsFormName, Integer demographicNo) {
    Integer fdid = getMaxFdid(nddsFormName, demographicNo);
    if (fdid == null) return null; // no un-uploaded form data

    EFormValue eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "subject");
    if (eformValue == null) return null;

    if (eformValue.getVarValue() != null
        && eformValue.getVarValue().toLowerCase().contains("draft")) {
      return null;
    }

    return fdid;
  }

  private Integer checkReport18mDone(String report18mFormName, Integer demographicNo) {
    Integer fdid = getMaxFdid(report18mFormName, demographicNo);
    if (fdid == null) return null; // no un-uploaded form data

    EFormValue eformValue = eformValueDao.findByFormDataIdAndKey(fdid, "subject");
    if (eformValue == null) return null;

    if (eformValue.getVarValue() != null
        && eformValue.getVarValue().toLowerCase().contains("draft")) {
      return null;
    }

    return fdid;
  }

  private byte[] generateXml(
      Integer demographicNo, Integer rourkeFdid, Integer nddsFdid, Integer report18mFdid) {
    HashMap<String, String> suggestedPrefixes = new HashMap<String, String>();
    suggestedPrefixes.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
    XmlOptions opts = new XmlOptions();
    opts.setSaveSuggestedPrefixes(suggestedPrefixes);
    opts.setSavePrettyPrint();
    opts.setSaveNoXmlDecl();
    opts.setUseDefaultNamespace();
    opts.setSaveNamespacesFirst();
    ByteArrayOutputStream os = null;
    PrintWriter pw = null;
    boolean xmlCreated = false;

    BORN18MFormToXML xml = new BORN18MFormToXML(demographicNo);
    try {
      os = new ByteArrayOutputStream();
      pw = new PrintWriter(os, true);
      pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      xmlCreated = xml.addXmlToStream(pw, opts, rourkeFdid, nddsFdid, report18mFdid);

      pw.close();
      if (xmlCreated) return os.toByteArray();
    } catch (Exception e) {
      logger.warn("Unable to add record", e);
    }

    return null;
  }

  private BornTransmissionLog prepareLog() {
    BornTransmissionLog log = new BornTransmissionLog();
    log.setFilename(filenameStart);
    log.setSubmitDateTime(new Date());
    logDao.persist(log);

    return log;
  }

  private boolean uploadToBORN(byte[] xmlFile, String filename) {
    String documentDir = oscarProperties.getProperty("DOCUMENT_DIR");

    boolean success = false;
    if (documentDir != null && new File(documentDir).exists()) {
      FileOutputStream fos = null;
      try {
        File f = new File(documentDir + File.separator + filename);
        fos = new FileOutputStream(f);
        fos.write(xmlFile);

        success = BornFtpManager.upload18MEWBVDataToRepository(xmlFile, filename);
      } catch (IOException e) {
        logger.warn("Unabled to backup file to document dir", e);
      } finally {
        try {
          if (fos != null) fos.close();
        } catch (IOException e) {
          logger.warn("Fail to close file output stream", e);
        }
      }
    } else {
      logger.warn("Cannot find DOCUMENT_DIR");
    }
    return success;
  }

  private void recordFormSent(
      Integer demographicNo, Integer rourkeFdid, Integer nddsFdid, Integer report18mFdid) {
    List<Integer> fdids = new ArrayList<Integer>();
    if (rourkeFdid != null) fdids.add(rourkeFdid);
    if (nddsFdid != null) fdids.add(nddsFdid);
    if (report18mFdid != null) fdids.add(report18mFdid);

    for (Integer fdid : fdids) {
      Integer fid = eformDataDao.find(fdid).getFormId();
      EFormValue eformValue = new EFormValue();
      eformValue.setDemographicId(Integer.valueOf(demographicNo));
      eformValue.setFormDataId(fdid);
      eformValue.setFormId(fid);
      eformValue.setVarName(UPLOADED_TO_BORN);
      eformValue.setVarValue(VALUE_YES);
      eformValueDao.persist(eformValue);
    }
  }

  private boolean checkDate18m(Date formDate, Integer demographicNo) {
    Calendar babyBirthday = demographicDao.getDemographic(demographicNo.toString()).getBirthDay();

    if (UtilDateUtilities.getNumMonths(babyBirthday.getTime(), formDate) < 18) {
      return false;
    }
    return true;
  }

  private Integer getMaxFdid(String formName, Integer demographicNo) {
    List<EFormData> eformDatas =
        eformDataDao.findByDemographicIdAndFormName(demographicNo, formName);
    if (eformDatas == null || eformDatas.isEmpty()) {
      logger.warn(formName + " form data not found for patient #" + demographicNo);
      return null;
    }

    Integer fdid = null;
    for (EFormData eformData : eformDatas) {
      if (fdid == null || fdid < eformData.getId()) {
        fdid = eformData.getId();
      }
    }
    if (!checkUploadedToBorn(fdid)) return fdid;
    else return null;
  }

  private boolean hasFormUploaded(String formName, Integer demographicNo) {
    List<EFormData> eformDatas =
        eformDataDao.findByDemographicIdAndFormName(demographicNo, formName);
    if (eformDatas == null || eformDatas.isEmpty()) {
      return false;
    }

    for (EFormData eformData : eformDatas) {
      if (checkUploadedToBorn(eformData.getId())) return true;
    }
    return false;
  }

  private boolean checkUploadedToBorn(Integer fdid) {
    EFormValue value = eformValueDao.findByFormDataIdAndKey(fdid, UPLOADED_TO_BORN);
    return (value != null && value.getVarValue().equals(VALUE_YES));
  }

  private String getFileSuffix(Integer logId) {
    long num = logDao.getSeqNoToday(filenameStart, logId);
    String tmp = String.valueOf(num);
    while (tmp.length() < 3) {
      tmp = "0" + tmp;
    }
    return tmp;
  }
}