/**
   * UTS authenticate.
   *
   * @param username the username
   * @param password the password
   * @return the string
   * @throws Exception the exception
   */
  @SuppressWarnings("unused")
  private String utsAuthenticate(String username, String password) throws Exception {
    final String utsSecurityUrl = config.getProperty("ihtsdo.security.url");
    final String licenseCode = config.getProperty("ihtsdo.security.license.code");
    if (licenseCode == null) {
      throw new Exception("License code must be specified.");
    }
    if (licenseCode == null) {
      throw new Exception("Security URL must be specified.");
    }

    String data =
        URLEncoder.encode("licenseCode", "UTF-8") + "=" + URLEncoder.encode(licenseCode, "UTF-8");
    data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    data +=
        "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    Logger.getLogger(getClass()).debug(data);
    URL url = new URL(utsSecurityUrl);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    boolean authenticated = false;
    while ((line = rd.readLine()) != null) {
      Logger.getLogger(getClass()).debug(line);
      if (line.toLowerCase().contains("true")) {
        authenticated = true;
      }
    }
    wr.close();
    rd.close();

    if (!authenticated) {
      throw new LocalException("Incorrect user name or password.");
    }

    /*
     * Synchronize the information sent back from ITHSDO with the MapUser
     * object. Add a new map user if there isn't one matching the username If
     * there is, load and update that map user and save the changes
     */
    String userName = username;
    String email = "*****@*****.**";
    String givenName = "UTS User - " + username;
    String surname = "";

    // check if ihtsdo user matches one of our MapUsers
    MappingService mappingService = new MappingServiceJpa();
    MapUserList userList = mappingService.getMapUsers();
    MapUser userFound = null;
    for (MapUser user : userList.getMapUsers()) {
      if (user.getUserName().equals(userName)) {
        userFound = user;
        break;
      }
    }
    // if MapUser not found, add it (as a viewer)
    if (userFound == null) {
      MapUser newMapUser = new MapUserJpa();
      newMapUser.setName(givenName + " " + surname);
      newMapUser.setUserName(userName);
      newMapUser.setEmail(email);
      newMapUser.setApplicationRole(MapUserRole.VIEWER);
      mappingService.addMapUser(newMapUser);
    }
    mappingService.close();

    // Generate application-managed token
    String token = UUID.randomUUID().toString();
    tokenUsernameMap.put(token, userName);
    tokenLoginMap.put(token, new Date());

    Logger.getLogger(this.getClass()).info("User = " + username);

    return token;
  }
  /**
   * IHTSDO authenticate.
   *
   * @param username the username
   * @param password the password
   * @return the string
   * @throws Exception the exception
   */
  @SuppressWarnings("unchecked")
  private String ihtsdoAuthenticate(String username, String password) throws Exception {

    String ihtsdoSecurityUrl = config.getProperty("ihtsdo.security.url");

    // set up request to be posted to ihtsdo security service
    Form form = new Form();
    form.add("username", username);
    form.add("password", password);
    form.add("queryName", "getUserByNameAuth");

    Client client = Client.create();
    WebResource resource = client.resource(ihtsdoSecurityUrl);

    resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE);

    ClientResponse response = resource.post(ClientResponse.class, form);

    String resultString = "";
    if (response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
      resultString = response.getEntity(String.class);
    } else {
      // TODO Differentiate error messages with NO RESPONSE and
      // Authentication Failed (Check text)
      Logger.getLogger(this.getClass()).info("ERROR! " + response.getStatus());
      resultString = response.getEntity(String.class);
      Logger.getLogger(this.getClass()).info(resultString);
      throw new LocalException("Incorrect user name or password.");
    }

    /*
     * Synchronize the information sent back from ITHSDO with the MapUser
     * object. Add a new map user if there isn't one matching the username If
     * there is, load and update that map user and save the changes
     */
    String ihtsdoUserName = "";
    String ihtsdoEmail = "";
    String ihtsdoGivenName = "";
    String ihtsdoSurname = "";

    // converting json to Map
    byte[] mapData = resultString.getBytes();
    Map<String, HashMap<String, String>> jsonMap = new HashMap<>();

    // parse username from json object
    ObjectMapper objectMapper = new ObjectMapper();
    jsonMap = objectMapper.readValue(mapData, HashMap.class);
    for (Entry<String, HashMap<String, String>> entrySet : jsonMap.entrySet()) {
      if (entrySet.getKey().equals("user")) {
        HashMap<String, String> innerMap = entrySet.getValue();
        for (Entry<String, String> innerEntrySet : innerMap.entrySet()) {
          if (innerEntrySet.getKey().equals("name")) {
            ihtsdoUserName = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("email")) {
            ihtsdoEmail = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("givenName")) {
            ihtsdoGivenName = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("surname")) {
            ihtsdoSurname = innerEntrySet.getValue();
          }
        }
      }
    }
    // check if ihtsdo user matches one of our MapUsers
    MappingService mappingService = new MappingServiceJpa();
    MapUserList userList = mappingService.getMapUsers();
    MapUser userFound = null;
    for (MapUser user : userList.getMapUsers()) {
      if (user.getUserName().equals(ihtsdoUserName)) {
        userFound = user;
        break;
      }
    }
    // if MapUser was found, update to match ihtsdo settings
    if (userFound != null) {
      userFound.setEmail(ihtsdoEmail);
      userFound.setName(ihtsdoGivenName + " " + ihtsdoSurname);
      userFound.setUserName(ihtsdoUserName);
      mappingService.updateMapUser(userFound);
      // if MapUser not found, create one for our use
    } else {
      MapUser newMapUser = new MapUserJpa();
      newMapUser.setName(ihtsdoGivenName + " " + ihtsdoSurname);
      newMapUser.setUserName(ihtsdoUserName);
      newMapUser.setEmail(ihtsdoEmail);
      newMapUser.setApplicationRole(MapUserRole.VIEWER);
      mappingService.addMapUser(newMapUser);
    }
    mappingService.close();

    // Generate application-managed token
    String token = UUID.randomUUID().toString();
    tokenUsernameMap.put(token, ihtsdoUserName);
    tokenLoginMap.put(token, new Date());

    Logger.getLogger(this.getClass()).info("User = " + resultString);

    return token;
  }