class KerberosOperationHandler {

  protected Keytab mergeKeytabs(Keytab keytab, Keytab updates) {
    List<KeytabEntry> keytabEntries = (keytab == null)
        ? Collections.emptyList()
        : new ArrayList<>(keytab.getEntries());
    List<KeytabEntry> updateEntries = (updates == null)
        ? Collections.emptyList()
        : new ArrayList<>(updates.getEntries());
    List<KeytabEntry> mergedEntries = new ArrayList<>();

    if (keytabEntries.isEmpty()) {
      mergedEntries.addAll(updateEntries);
    } else if (updateEntries.isEmpty()) {
      mergedEntries.addAll(keytabEntries);
    } else {
      Iterator<KeytabEntry> iterator = keytabEntries.iterator();

      while (iterator.hasNext()) {
        KeytabEntry keytabEntry = iterator.next();

        for (KeytabEntry entry : updateEntries) {
          if (entry.getPrincipalName().equals(keytabEntry.getPrincipalName()) &&
              entry.getKey().getKeyType().equals(keytabEntry.getKey().getKeyType())) {
            iterator.remove();
            break;
          }
        }
      }

      mergedEntries.addAll(keytabEntries);
      mergedEntries.addAll(updateEntries);
    }

    Keytab mergedKeytab = new Keytab();
    mergedKeytab.setEntries(mergedEntries);
    return mergedKeytab;
  }

}