public static String perConnectionAuthorizationHeader(
      Request request, ProxyServer proxyServer, Realm realm) {
    String authorizationHeader = null;

    if (realm != null && realm.getUsePreemptiveAuth()) {
      switch (realm.getScheme()) {
        case NTLM:
          String msg = NtlmEngine.INSTANCE.generateType1Msg();
          authorizationHeader = "NTLM " + msg;
          break;
        case KERBEROS:
        case SPNEGO:
          String host;
          if (proxyServer != null) host = proxyServer.getHost();
          else if (request.getVirtualHost() != null) host = request.getVirtualHost();
          else host = request.getUri().getHost();

          authorizationHeader = "Negotiate " + SpnegoEngine.instance().generateToken(host);
          break;
        default:
          break;
      }
    }

    return authorizationHeader;
  }
  public static String perRequestAuthorizationHeader(Request request, Realm realm) {

    String authorizationHeader = null;

    if (realm != null && realm.getUsePreemptiveAuth()) {

      switch (realm.getScheme()) {
        case BASIC:
          authorizationHeader = computeBasicAuthentication(realm);
          break;
        case DIGEST:
          if (isNonEmpty(realm.getNonce()))
            authorizationHeader = computeDigestAuthentication(realm);
          break;
        case NTLM:
        case KERBEROS:
        case SPNEGO:
          // NTLM, KERBEROS and SPNEGO are only set on the first request,
          // see firstRequestOnlyAuthorizationHeader
        case NONE:
          break;
        default:
          throw new IllegalStateException("Invalid Authentication " + realm);
      }
    }

    return authorizationHeader;
  }
  public static String perRequestProxyAuthorizationHeader(
      Request request, ProxyServer proxyServer, Realm realm, boolean connect) {

    String proxyAuthorization = null;

    if (!connect && proxyServer != null && proxyServer.getScheme() == AuthScheme.BASIC) {
      proxyAuthorization = computeBasicAuthentication(proxyServer);
    } else if (realm != null && realm.getUsePreemptiveAuth() && realm.isTargetProxy()) {

      switch (realm.getScheme()) {
        case BASIC:
          proxyAuthorization = computeBasicAuthentication(realm);
          break;
        case DIGEST:
          if (isNonEmpty(realm.getNonce())) proxyAuthorization = computeDigestAuthentication(realm);
          break;
        case NTLM:
        case KERBEROS:
        case SPNEGO:
          // NTLM, KERBEROS and SPNEGO are only set on the first request,
          // see firstRequestOnlyAuthorizationHeader
        case NONE:
          break;
        default:
          throw new IllegalStateException("Invalid Authentication " + realm);
      }
    }

    return proxyAuthorization;
  }