/**
  * @param targetService
  * @return a proxy ticket.
  * @throws CasException
  */
 private String retrieveProxyTicket(final String targetService) throws CasException {
   if (logger.isDebugEnabled()) {
     logger.debug("retrieving a proxy ticket for service [" + targetService + "]...");
     logger.debug("pgtIou=[" + validator.getPgtIou() + "]");
   }
   int tryNumber = 0;
   Exception exception = null;
   while (tryNumber < (1 + retries)) {
     tryNumber++;
     if (logger.isDebugEnabled()) {
       logger.debug("try #" + tryNumber);
     }
     try {
       String url = URLEncoder.encode(targetService, "UTF-8");
       return ProxyTicketReceptor.getProxyTicket(validator.getPgtIou(), url);
     } catch (IOException e) {
       if (logger.isDebugEnabled()) {
         logger.debug(
             "could not retrieve a proxy ticket for service ["
                 + targetService
                 + "] (try #"
                 + tryNumber
                 + ")",
             e);
       }
       if (tryNumber == retries) {
         try {
           Thread.sleep(sleep * THOUSAND);
         } catch (InterruptedException ie) {
           exception = ie;
         }
       } else {
         exception = e;
       }
     }
   }
   CasException ce =
       new CasException(
           "could not get a proxy ticket for service [" + targetService + "]", exception);
   if (logger.isDebugEnabled()) {
     logger.debug(ce);
   }
   throw ce;
 }
 /** @see org.esupportail.commons.services.cas.CasService#validate() */
 public void validate() throws CasException {
   String serviceTicket = getServiceTicket();
   validator = new ProxyTicketValidator();
   validator.setCasValidateUrl(casValidateUrl);
   validator.setService(service);
   validator.setServiceTicket(serviceTicket);
   validator.setProxyCallbackUrl(proxyCallbackUrl);
   if (logger.isDebugEnabled()) {
     logger.debug("validating ticket [" + serviceTicket + "]...");
     logger.debug("casValidateUrl=[" + validator.getCasValidateUrl() + "]");
     logger.debug("service=[" + service + "]");
     logger.debug("proxyCallbackUrl=[" + validator.getProxyCallbackUrl() + "]");
   }
   int tryNumber = 0;
   Exception validateException = null;
   while (tryNumber < (1 + retries)) {
     tryNumber++;
     if (logger.isDebugEnabled()) {
       logger.debug("try #" + tryNumber);
     }
     try {
       validator.validate();
       if (logger.isDebugEnabled()) {
         logger.debug("response = [" + validator.getResponse() + "]");
         logger.debug("errorCode = [" + validator.getErrorCode() + "]");
         logger.debug("errorMessage = [" + validator.getErrorMessage() + "]");
       }
       if (validator.isAuthenticationSuccesful()) {
         return;
       }
       // no error, but authentication failed
       throw new CasException(
           "authentication failed for ticket ["
               + serviceTicket
               + "] ("
               + validator.getErrorCode()
               + ": "
               + validator.getErrorMessage()
               + ")");
     } catch (IOException e) {
       if (logger.isDebugEnabled()) {
         logger.debug(
             "could not validate ticket [" + serviceTicket + "] (try #" + tryNumber + ")", e);
       }
       if (tryNumber == retries) {
         try {
           Thread.sleep(sleep * THOUSAND);
         } catch (InterruptedException ie) {
           validateException = ie;
         }
       } else {
         validateException = e;
       }
     } catch (SAXException e) {
       validateException = e;
     } catch (ParserConfigurationException e) {
       validateException = e;
     }
   }
   CasException ce =
       new CasException("could not validate ticket [" + serviceTicket + "]", validateException);
   if (logger.isDebugEnabled()) {
     logger.debug(ce);
   }
   throw ce;
 }
  /** This method authenticates against the infoglue extranet user database. */
  private String authenticate(String ticket) throws Exception {
    boolean isAuthenticated = false;

    if (logger.isInfoEnabled()) {
      try {
        throw new Exception("authenticate called with ticket:" + ticket);
      } catch (Exception e) {
        if (logger.isInfoEnabled()) logger.info("DEBUG:" + e.getMessage(), e);
      }
    }

    logger.info("ticket:" + ticket);
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
              logger.info("Checking if client is trusted...");
            }
            /*
            public void checkServerTrusted(X509Certificate[] certs, String authType)
            {
            	logger.info("Checking if server is trusted...");
            }
            */

            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
              // TODO Auto-generated method stub

            }
          }
        };

    HostnameVerifier hv =
        new HostnameVerifier() {
          public boolean verify(String urlHostName, SSLSession session) {
            logger.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            return true;
          }
        };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    String authenticatedUserName = null;

    /* instantiate a new ProxyTicketValidator */
    ProxyTicketValidator pv = new ProxyTicketValidator();

    /* set its parameters */
    // pv.setCasValidateUrl(casValidateUrl);

    String encodeValidateUrl = CmsPropertyHandler.getEncodeValidateUrl();
    String encodeCasServiceUrl = CmsPropertyHandler.getEncodeCasServiceUrl();

    if (ticket != null && ticket.substring(0, 2).equals("PT")) {
      if (encodeValidateUrl != null && encodeValidateUrl.equals("true"))
        casProxyValidateUrl = URLEncoder.encode(casProxyValidateUrl, "iso-8859-1");

      logger.info("setting casProxyValidateUrl: " + casProxyValidateUrl);
      pv.setCasValidateUrl(casProxyValidateUrl);

    } else {
      if (encodeValidateUrl != null && encodeValidateUrl.equals("true"))
        casValidateUrl = URLEncoder.encode(casValidateUrl, "iso-8859-1");

      pv.setCasValidateUrl(casValidateUrl);
      logger.info("setting casValidateUrl: " + casValidateUrl);
    }

    if (encodeCasServiceUrl != null && encodeCasServiceUrl.equals("true"))
      casServiceUrl = URLEncoder.encode(casServiceUrl, "iso-8859-1");

    logger.info("validating: " + casServiceUrl);
    pv.setService(casServiceUrl);

    pv.setServiceTicket(ticket);

    /*
     * If we want to be able to acquire proxy tickets (requires callback servlet to be set up
     * in web.xml - see below)
     */

    /* contact CAS and validate */

    try {
      // ----------------------------------------------------------------------
      // If this is a CAS 2.0 installation the response will be in XML format.
      // If this is a CAS 1.0 the response will be a simple String and the
      // pv.validate() method will throw an exception
      // ("content not allowed in prolog"). If this exception is thrown we
      // will do a further check in the catch and see if the user was
      // verified even though the response was not in XML.
      // -----------------------------------------------------------------------

      pv.validate();

      /* if we want to look at the raw response, we can use getResponse() */
      String xmlResponse = pv.getResponse();
      logger.info("xmlResponse:" + xmlResponse);

      /* read the response */
      if (pv.isAuthenticationSuccesful()) {
        String user = pv.getUser();
        List proxyList = pv.getProxyList();
        authenticatedUserName = pv.getUser();

        logger.info("The user " + user + " was authenticated successfully.");
      } else {
        String errorCode = pv.getErrorCode();
        String errorMessage = pv.getErrorMessage();
        /* handle the error */
      }

      /* The user is now authenticated. */
      /* If we did set the proxy callback url, we can get proxy tickets with: */

      logger.info("proxies:\n " + pv.getProxyList());
    } catch (Exception e) {
      logger.info("-------------------------------------------------------------");
      logger.info("(Johans utskrift)  Felmeddelande: " + e.getMessage());
      logger.info("(Johans utskrift)  pv.getCasValidateUrl: " + pv.getCasValidateUrl());
      logger.info("(Johans utskrift)  pv.getErrorCode(): " + pv.getErrorCode());
      logger.info("(Johans utskrift)  pv.getErrorMessage: " + pv.getErrorMessage());
      logger.info("(Johans utskrift)  pv.getPgtIou: " + pv.getPgtIou());
      logger.info("(Johans utskrift)  pv.getProxyCallbackUrl: " + pv.getProxyCallbackUrl());
      logger.info("(Johans utskrift)  pv.getResponse: " + pv.getResponse());
      logger.info("(Johans utskrift)  pv.getUser: "******"(Johans utskrift)  pv.getClass: " + pv.getClass());
      logger.info("(Johans utskrift)  pv.getProxyList: " + pv.getProxyList());
      logger.info("-------------------------------------------------------------");

      // --------------------------------------------------------------------
      // Check if the user was authenticated even though an exception occured.
      // This will be the case if the CAS is a 1.0 installation.
      // --------------------------------------------------------------------

      String casResponse = pv.getResponse();

      logger.info("CAS RESPONSE: " + casResponse.substring(0, 3));

      String response = casResponse.substring(0, casResponse.indexOf('\n'));
      String userId = casResponse.substring(casResponse.indexOf('\n') + 1);

      if (response.equals("yes")) {
        logger.info(
            "The user "
                + userId
                + " was authenticated successfully against a CAS 1.0 installation");

        authenticatedUserName = userId.trim();
      } else if (response.equals("no")) {
        logger.info("Permission denied for the user " + userId + " against a CAS 1.0 installation");
        // Do nothing
      } else {
        // ------------------------------------------------------------
        // Some other error occured and we throw the Exception again.
        // ------------------------------------------------------------

        throw e;
      }
    }

    return authenticatedUserName;
  }