public synchronized IAddress[] getAddress(
      IAddress searchCriteria, String searchTypeText, String listItem, String searchStatus)
      throws PresentationLogicException {
    // WDEV-17296
    String lSearchText = searchCriteria.getAddressSearchText();
    // WDEV-17296

    if (searchCriteria == null) {
      throw new PresentationLogicException("No address search criteria provided.");
    }

    ims.core.vo.PersonAddress[] l_address_results;
    ims.core.vo.PersonAddress l_address = new ims.core.vo.PersonAddress();

    select = new Vector<String>();
    where = new Vector();
    data = new Vector();

    l_address =
        (PersonAddress) searchForAddress(searchCriteria, searchTypeText, listItem, searchStatus);

    if (l_address == null) return null;

    int ambiguitySize = getAmbiguitySize();

    l_address_results = new ims.core.vo.PersonAddress[ambiguitySize + 1];
    l_address_results[0] = l_address;

    l_address_results = getAmbiguityList(l_address_results);

    // WDEV-16590
    String ccgCode = null;
    if (ConfigFlag.UI.DISPLAY_PCT_CODE.getValue()
        && l_address != null
        && l_address.getPostCodeIsNotNull()) {
      String pCode = l_address.getPostCode().replaceAll(" ", "");

      // WDEV-17296
      if (pCode == null || pCode.equals("")) {
        pCode = lSearchText.replaceAll(" ", "");
      }
      // WDEV-17296

      CCGPCTPCCodes domCCG = CCGPCTPCCodes.getCCGPCTPCCodesFromPostcode(getDomainFactory(), pCode);
      if (domCCG != null && domCCG.getCCGCode() != null) {
        l_address.setPCT(domCCG.getCCGCode());
        l_address_results[0].setPCT(domCCG.getCCGCode());
        l_address_results[0].setPCTcode(domCCG.getCCGCode());
      } else {
        l_address_results[0].setPCT(null);
        l_address_results[0].setPCTcode(null);
      }
    }

    return l_address_results;
  }
  @SuppressWarnings("static-access")
  private HashMap<String, String> searchForDistance(IAddress searchCriteria, String units) {

    StringBuilder l_query = new StringBuilder();
    StringBuilder l_restQuery = new StringBuilder();

    l_query.append(units + ",NEARESTRECORDS from PSEARCH");

    if (searchCriteria.getAddressPostCode() == null) return null;

    String strPostCode = stripspaces(searchCriteria.getAddressPostCode().toString());

    if (strPostCode.length() > 7) {
      strPostCode = strPostCode.substring(0, 7); // only take full postcode for nearcode criteria
    }

    l_restQuery.append(" WHERE ADDR=" + "\"" + strPostCode + "\"");

    // apply radius
    if (ConfigFlag.UI.CAPSCAN_DIST_SEARCH_RADIUS.getValue() != ""
        && !ConfigFlag.UI.CAPSCAN_DIST_SEARCH_RADIUS.getValue().equals("-1"))
      l_restQuery.append(",RADIUS=" + ConfigFlag.UI.CAPSCAN_DIST_SEARCH_RADIUS.getValue());

    // apply maxrecords
    if (ConfigFlag.UI.CAPSCAN_DIST_MAX_RECORDS.getValue() != "")
      l_restQuery.append(",MAXRECORDS=" + ConfigFlag.UI.CAPSCAN_DIST_MAX_RECORDS.getValue());

    l_query.append(l_restQuery);

    try {
      parseQuery(l_query.toString());
      LOG.info("Nearcode Query: " + l_query.toString());
    } catch (Exception e) {
      LOG.error(e.getMessage());
      return null;
    }

    capscan.client.NcConnection distanceManagerConnection = null;

    try {
      // WDEV-17607
      distanceManagerConnection = AddressManager.getncConnection();
      if (distanceManagerConnection == null
          || (distanceManagerConnection != null && distanceManagerConnection.errno() != 0)) {
        AddressManager.ncConnect(
            EnvironmentConfig.getCapscanServerName(),
            EnvironmentConfig.getCapscanDistPool(),
            NcConnection.STATELESS);
        distanceManagerConnection = AddressManager.getncConnection();
      }
      // WDEV-17607

      distanceManagerConnection = AddressManager.getncConnection();
    } catch (Exception e) {
      LOG.error(e.getMessage());
      return null;
    }

    if (distanceManagerConnection == null) {
      LOG.error(
          "Error getting Distance Manager connection. Please see server logs for more information.");
      return null;
    }

    resultsSearch = distanceManagerConnection.search(searchType, select, where, data, 15);

    if (resultsSearch != null
        && distanceManagerConnection != null
        && distanceManagerConnection.errno() == capscan.client.NcConnection.OK) {
      if (select.size() > 1) {
        // fill Map here
        String pools[] = distanceManagerConnection.pools();
        LOG.info("QUERY RESULTS");
        pools = distanceManagerConnection.pools();
        String column;
        int count = 0;
        int k;
        int j;
        count = resultsSearch.length;
        StringBuffer strUnitDistances, strCodes;

        strUnitDistances = new StringBuffer();
        strCodes = new StringBuffer();

        for (j = k = 0; j < pools.length; j++) {
          if (pools.length > 1) {
            LOG.info("Pool " + pools[j] + ":\r\n");
          }

          // Get unit distances first
          for (k = 0; k < count; k++) {
            if (k < select.size()) column = (String) select.elementAt(k);
            else column = "";
            if (column.equals("MILES") || column.equals("KILOMETERS"))
              strUnitDistances.append(resultsSearch[k]);
          }

          // get corresponding codes
          for (k = 0; k < count; k++) {
            if (k < select.size()) column = (String) select.elementAt(k);
            else column = "";
            if (column.equals("NEARESTRECORDS")) strCodes.append(resultsSearch[k]);
          }
        }

        putResultDistanceAndCode(strUnitDistances, strCodes);
      }
    } else {
      if (distanceManagerConnection != null) {
        LOG.error(
            "error: " + distanceManagerConnection.strerror(distanceManagerConnection.errno()));
        return null;
      } else {
        LOG.error("error: connection null");
        return null;
      }
    }

    if (resultMap == null) return null;

    return new HashMap<String, String>(resultMap);
  }
  private synchronized IAddress searchForAddress(
      IAddress searchCriteria, String searchTypeText, String listItem, String searchStatus)
      throws PresentationLogicException {
    // LOG.info("getAddressByPostcode:");

    if (searchCriteria == null) throw new PresentationLogicException("No Search Criteria given.");

    // select
    // AMBIGLIST,ORGANISATION,SUBBUILDING,BUILDINGNAME,BUILDINGNUMBER,DEPSTREET,STREET,DEPLOCALITY,LOCALITY,POSTTOWN,COUNTY,POSTCODE,ADDR,ADDKEY,ORGKEY,LISTTYPE,SEARCHSTATUS,LISTCOUNT,AMBIGLIST,BARCODE,ADEPOS,ADESCORE,ADPNRLOC,MSCORE,FFLAG,RESCODE,ERRNO,ERRTEXT,COUNTRY,COUNTRYCODE,MATCHLVL,PCLVL,INPCLVL,PCCHGLVL,PCCHGTYP,VANITYFLAGS,ELEMS_UNMATCHED,ELEMS_MATCHED,ELEMS_CORRECT,ELEMS_MISSPELLED,ELEMS_MISSING,FIELDSTATUS,OUTPUTSTATUS,ADDFMT_ABBR,ADDFMT_CONC,ADDFMT_TRUN,ADDFMT_ELIM,ADMINNUMBER,TRADNUMBER,LONLOCOUT,ADMINCOUNTY,TRADCOUNTY from PCLOOKUP where POSTCODE=

    StringBuilder l_query = new StringBuilder();
    StringBuilder l_restQuery = new StringBuilder();
    StringBuilder l_queryType = new StringBuilder();

    l_query.append(
        "AMBIGLIST,ORGANISATION,SUBBUILDING,BUILDINGNAME,BUILDINGNUMBER,"
            + "DEPSTREET,STREET,DEPLOCALITY,LOCALITY,POSTTOWN,COUNTY,"
            + "POSTCODE(PP=16),ADDR,ADDKEY,ORGKEY,LISTTYPE,SEARCHSTATUS,"
            + "LISTCOUNT,AMBIGLIST,BARCODE,ADEPOS,ADESCORE,ADPNRLOC,"
            + "MSCORE,FFLAG,RESCODE,ERRNO,ERRTEXT,COUNTRY,COUNTRYCODE,"
            + "MATCHLVL,PCLVL,INPCLVL,PCCHGLVL,PCCHGTYP,VANITYFLAGS,"
            + "ELEMS_UNMATCHED,ELEMS_MATCHED,ELEMS_CORRECT,"
            + "ELEMS_MISSPELLED,ELEMS_MISSING,FIELDSTATUS,"
            + "OUTPUTSTATUS,ADDFMT_ABBR,ADDFMT_CONC,ADDFMT_TRUN,"
            + "ADDFMT_ELIM,ADMINNUMBER,TRADNUMBER,LONLOCOUT,ADMINCOUNTY,"
            + "TRADCOUNTY,PCG,DHA,OLDPCG,OLDDHA from "); // WDEV-14455

    String postcode = "";
    String Addr = "";
    String buildingNumber = "";
    String street = "";
    String postTown = "";
    String county = "";

    l_restQuery.append("");

    if (searchTypeText.equals("SEARCH")) {
      if (searchCriteria.getAddressSearchText() != null
          && searchCriteria.getAddressSearchText() != "") {
        Addr = searchCriteria.getAddressSearchText();
        if (l_restQuery.length() == 0) l_restQuery.append(" WHERE ADDR=" + "\"" + Addr + "\"");
      }
    } else if (searchTypeText.equals("SELECT")) {
      if (searchCriteria.getAddressPostCode() != null) {
        postcode = searchCriteria.getAddressPostCode().toString();
        l_restQuery.append(" WHERE POSTCODE=" + "\"" + postcode + "\"");
      }

      if (searchStatus != null && !searchStatus.equals("")) {
        if (l_restQuery.length() == 0)
          l_restQuery.append(" WHERE SEARCHSTATUS=" + "\"" + searchStatus + "\"");
        else l_restQuery.append(",SEARCHSTATUS=" + "\"" + searchStatus + "\"");
      }

      if (searchCriteria.getAddressBuildingNumber() != null
          && searchCriteria.getAddressBuildingNumber() != "") {
        buildingNumber = searchCriteria.getAddressBuildingNumber().toString();
        if (l_restQuery.length() == 0)
          l_restQuery.append(" WHERE BUILDINGNUMBER=" + "\"" + buildingNumber + "\"");
        else l_restQuery.append(",BUILDINGNUMBER=" + "\"" + buildingNumber + "\"");
      }
      if (searchCriteria.getAddressStreet() != null && searchCriteria.getAddressStreet() != "") {
        street = searchCriteria.getAddressStreet().toString();
        if (l_restQuery.length() == 0) l_restQuery.append(" WHERE STREET=" + "\"" + street + "\"");
        else l_restQuery.append(",STREET=" + "\"" + street + "\"");
      }

      if (searchCriteria.getAddressPostTown() != null
          && searchCriteria.getAddressPostTown() != "") {
        postTown = searchCriteria.getAddressPostTown().toString();
        if (l_restQuery.length() == 0)
          l_restQuery.append(" WHERE POSTTOWN=" + "\"" + postTown + "\"");
        else l_restQuery.append(",POSTTOWN=" + "\"" + postTown + "\"");
      }
      if (searchCriteria.getAddressCounty() != null && searchCriteria.getAddressCounty() != "") {
        county = searchCriteria.getAddressCounty().toString();
        if (l_restQuery.length() == 0) l_restQuery.append(" WHERE COUNTY=" + "\"" + county + "\"");
        else l_restQuery.append(",COUNTY=" + "\"" + county + "\"");
      }

      // ListItem for Ambiguity selection
      if (listItem != null && listItem != "") {
        if (l_restQuery.length() == 0)
          l_restQuery.append(" WHERE LISTITEM=" + "\"" + listItem + "\"");
        else l_restQuery.append(",LISTITEM=" + "\"" + listItem + "\"");
      }
    } else if (searchTypeText.equals("PCLOOKUP")) {
      if (searchCriteria.getAddressPostCode() != null) {
        postcode = searchCriteria.getAddressPostCode().toString();
        l_restQuery.append(" WHERE POSTCODE=" + "\"" + postcode + "\"");
      }
    }

    l_queryType.append(searchTypeText);

    l_query.append(l_queryType);
    l_query.append(l_restQuery);

    try {
      parseQuery(l_query.toString());
      LOG.info("CAPSCAN Query: " + l_query.toString());
    } catch (Exception e) {
      LOG.error(e.getMessage());
      return null;
    }

    capscan.client.McConnection addressManagerConnection = null;

    try {
      // WDEV-17607
      addressManagerConnection = AddressManager.getConnection();
      if (addressManagerConnection == null
          || (addressManagerConnection != null && addressManagerConnection.errno() != 0)
          || (addressManagerConnection != null && addressManagerConnection.errno() != 1)) {
        AddressManager.connect(
            EnvironmentConfig.getCapscanServerName(),
            EnvironmentConfig.getCapscanPool(),
            McConnection.STATELESS);
        addressManagerConnection = AddressManager.getConnection();
      }
      // WDEV-17607
    } catch (Exception e) {
      LOG.error(e.getMessage());
      return null;
    }

    if (addressManagerConnection == null) {
      LOG.error(
          "Error getting Address Manager connection. Please see server logs for more information.");
      return null;
    }

    // WDEV-19795
    int EventId =
        createSystemLogEntry(
                SystemLogType.PostCodeLookup,
                SystemLogLevel.INFORMATION,
                "Postcode lookup:"
                    + select.toString()
                    + " "
                    + where.toString()
                    + " "
                    + data.toString())
            .getSystemLogEventId();
    // WDEV-19795

    resultsSearch = addressManagerConnection.search(searchType, select, where, data, 15);

    if (resultsSearch != null
        && addressManagerConnection != null
        && addressManagerConnection.errno() == capscan.client.McConnection.OK) {
      // Display results
      // int count = results.length;

      //
      // use for logging search query at level ERROR

      String pools[] = addressManagerConnection.pools();
      LOG.info("QUERY RESULTS");
      pools = addressManagerConnection.pools();
      String column;
      int count = 0;
      int i;
      int k;
      int j;
      count = resultsSearch.length;

      for (j = k = 0; j < pools.length; j++) {
        if (pools.length > 1) {
          LOG.info("Pool " + pools[j] + ":\r\n");
        }

        for (i = 0; k < count && i < select.size(); i++, k++) {
          column = (String) select.elementAt(i);
          LOG.info(column + ":\r\n");
          if (column.equals("AMBIGLIST")) {
            printAmbigList(resultsSearch[k]);
          } else {
            LOG.info("\t" + resultsSearch[k] + "\r\n");
          }
        }
      }

      if (select.size() > 1) {
        String strSubBuildingName = getColumnValue("SUBBUILDING");
        boolean displaystrSubBuildingName = false;

        String strBuildingName = getColumnValue("BUILDINGNAME");
        if (strSubBuildingName != null && !strSubBuildingName.equals("")) {
          if (!strBuildingName.equals("")) {
            // WDEV-17696
            if (ConfigFlag.DOM.HEARTS_REPLICATE_PATIENTS.getValue()) {
              if (strSubBuildingName != null
                  && strBuildingName != null
                  && ConfigFlag.DOM.HEARTS_ADDRESS_LINE_MAXLEN != null) {
                if (strSubBuildingName.length() + strBuildingName.length()
                    <= ConfigFlag.DOM.HEARTS_ADDRESS_LINE_MAXLEN.getValue()) {
                  searchCriteria.setAddressBuildingName(
                      strSubBuildingName + ", " + strBuildingName);
                  displaystrSubBuildingName = true;
                } else searchCriteria.setAddressBuildingName(strBuildingName);
              } else searchCriteria.setAddressBuildingName(strBuildingName);
            } else searchCriteria.setAddressBuildingName(strBuildingName);
          } else searchCriteria.setAddressBuildingName(strSubBuildingName);
        } else {
          searchCriteria.setAddressBuildingName(strBuildingName);
        }

        searchCriteria.setAddressBuildingNumber(getColumnValue("BUILDINGNUMBER"));
        searchCriteria.setAddressLocality(getColumnValue("LOCALITY"));
        // WDEV-15963
        // support for DEPSTREET
        if (getColumnValue("DEPSTREET") != null && !getColumnValue("DEPSTREET").equals(""))
          searchCriteria.setAddressStreet(
              getColumnValue("DEPSTREET") + "," + getColumnValue("STREET"));
        else searchCriteria.setAddressStreet(getColumnValue("STREET"));

        // WDEV-17553
        searchCriteria.setAddressPostTown(getColumnValue("POSTTOWN"));
        if (getColumnValue("POSTTOWN") != null
            && !getColumnValue("POSTTOWN").equals(getColumnValue("COUNTY")))
          searchCriteria.setAddressCounty(getColumnValue("COUNTY"));
        else searchCriteria.setAddressCounty("");

        // WDEV-15963
        searchCriteria.setAddressPostCode(getColumnValue("POSTCODE(PP=16)"));
        searchCriteria.setAddressSearchText(getColumnValue("SEARCHSTATUS"));

        // WDEV-17696
        if (displaystrSubBuildingName)
          searchCriteria.setAddressOrganisation(getColumnValue("ORGANISATION"));
        else if (getColumnValue("ORGANISATION") != null) {

          String strSubBuildingNameNoComma =
              strSubBuildingName != null && strSubBuildingName.length() > 0
                  ? "," + strSubBuildingName
                  : ""; // WDEV-19643
          searchCriteria.setAddressOrganisation(
              !getColumnValue("ORGANISATION").equals("")
                  ? getColumnValue("ORGANISATION") + strSubBuildingNameNoComma
                  : strSubBuildingName);
        }
        // WDEV-14455
        if (ConfigFlag.UI.CAPSCAN_USE_OLDPCT_CODE.getValue()) {
          searchCriteria.setPCTcode(stripspaces(getColumnValue("OLDPCG")));
        } else {
          searchCriteria.setPCTcode(stripspaces(getColumnValue("PCG")));
        }
      }
    } else {
      if (addressManagerConnection != null) {
        LOG.error("error: " + addressManagerConnection.strerror(addressManagerConnection.errno()));
        return null;
      } else {
        LOG.error("error: connection null");
        return null;
      }
    }

    return searchCriteria;
  }
  private synchronized String[] getCoOrds(IAddress searchCriteria, LatitudeLogitudeFormat[] lformat)
      throws DomainRuntimeException {
    // DEGREES DEG
    // RADIANS RAD
    // SPACES  SPA Spaces instead of colons
    // SYMBOLS SYM Degrees, Minutes and Seconds symbols instead of colons
    // OSGB36  Ordnance Survey of Great Britain (default) datum (default)
    // WGS84   World Geodetic Standard 1984 datum

    LOG.info("getLatitudeLogitude:");

    if (searchCriteria == null && searchCriteria.getAddressPostCode() == null)
      throw new DomainRuntimeException("No Search Criteria given.");

    StringBuilder l_query = new StringBuilder();
    StringBuilder l_latitudeQuery = new StringBuilder();
    StringBuilder l_longitudeQuery = new StringBuilder();

    String strPostCode = stripspaces(searchCriteria.getAddressPostCode().toString());

    if (lformat == null) {
      l_query.append(" LATITUDE(DEG),LONGITUDE(DEG) from ");
    } else if (lformat.length == 1) {
      switch (lformat[0].getId()) {
        case LatitudeLogitudeFormat.EDEGREES:
          l_query.append(" LATITUDE(DEG),LONGITUDE(DEG) from ");
          break;
        case LatitudeLogitudeFormat.ERADIANS:
          l_query.append(" LATITUDE(RAD),LONGITUDE(RAD) from ");
          break;
        case LatitudeLogitudeFormat.ESPACES:
          l_query.append(" LATITUDE(SPA),LONGITUDE(SPA) from ");
          break;
        case LatitudeLogitudeFormat.ESYMBOLS:
          l_query.append(" LATITUDE(SYM),LONGITUDE(SYM) from ");
          break;
        default:
          l_query.append(" LATITUDE(DEG),LONGITUDE(DEG) from ");
          break;
      }
    } else if (lformat.length == 2) {
      // two formats specified
      switch (lformat[0].getId()) {
        case LatitudeLogitudeFormat.EDEGREES:
          l_latitudeQuery.append(" LATITUDE(DEG,");
          l_longitudeQuery.append(" LONGITUDE(DEG,");
          break;
        case LatitudeLogitudeFormat.ERADIANS:
          l_latitudeQuery.append(" LATITUDE(RAD,");
          l_longitudeQuery.append(" LONGITUDE(RAD,");
          break;
        case LatitudeLogitudeFormat.ESPACES:
          l_latitudeQuery.append(" LATITUDE(SPA,");
          l_longitudeQuery.append(" LONGITUDE(SPA,");
          break;
        case LatitudeLogitudeFormat.ESYMBOLS:
          l_latitudeQuery.append(" LATITUDE(SYM,");
          l_longitudeQuery.append(" LONGITUDE(SYM,");
          break;
        default:
          l_query.append(" LATITUDE(DEG),LONGITUDE(DEG) from ");
          break;
      }
      switch (lformat[1].getId()) {
        case LatitudeLogitudeFormat.ESPACES:
          l_latitudeQuery.append("SPA)");
          l_longitudeQuery.append("SPA)");
          break;
        case LatitudeLogitudeFormat.ESYMBOLS:
          l_latitudeQuery.append("SYM)");
          l_longitudeQuery.append("SYM)");
          break;
        case LatitudeLogitudeFormat.EOSGB36:
          l_latitudeQuery.append("OSGB36)");
          l_longitudeQuery.append("OSGB36)");
          break;
        case LatitudeLogitudeFormat.EWGS84:
          l_latitudeQuery.append("WGS84)");
          l_longitudeQuery.append("WGS84)");
          break;
        default:
          if (l_query.toString() == "") l_query.append(" LATITUDE(DEG),LONGITUDE(DEG) from ");
          else break;
          break;
      }
    }

    try {
      l_query.append("PCLOOKUP WHERE POSTCODE = " + strPostCode);
      parseQuery(l_query.toString());
      LOG.info("CAPSCAN GEO Query: " + l_query.toString());
    } catch (Exception e) {
      throw new DomainRuntimeException(e.getMessage());
    }

    capscan.client.McConnection addressManagerConnection = null;

    try {
      addressManagerConnection = AddressManager.getConnection();
    } catch (Exception e) {
      LOG.error(e.getMessage());
      return null;
    }

    if (addressManagerConnection == null) {
      LOG.error(
          "Error getting Address Manager connection. Please see server logs for more information.");
      return null;
    }

    resultsSearch = addressManagerConnection.search(searchType, select, where, data, 15);

    return resultsSearch;
  }