package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.Map;
import java.util.Iterator;
import org.openid4java.discovery.Identifier;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.*;
import org.openid4java.OpenIDException;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.InMemoryConsumerAssociationStore;
import org.openid4java.consumer.InMemoryNonceVerifier;

public final class consumer_005fredirect_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");

    // README:
    // Set the returnToUrl string to the appropriate value for this JSP
    // Since you may be deployed behind apache, etc, the jsp has no real idea what the
    // absolute URI is to get back here.

    Object o = pageContext.getAttribute("consumermanager", PageContext.APPLICATION_SCOPE);
    if (o == null)
    {
        ConsumerManager newmgr=new ConsumerManager();
        newmgr.setAssociations(new InMemoryConsumerAssociationStore());
        newmgr.setNonceVerifier(new InMemoryNonceVerifier(5000));
        pageContext.setAttribute("consumermanager", newmgr, PageContext.APPLICATION_SCOPE);
    }
    ConsumerManager manager=(ConsumerManager) pageContext.getAttribute("consumermanager", PageContext.APPLICATION_SCOPE);
    String openid=request.getParameter("openid");

        try
        {
            // determine a return_to URL where your application will receive
            // the authentication responses from the OpenID provider
            // YOU SHOULD CHANGE THIS TO GO TO THE
            String returnToUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/simple-openid/consumer_returnurl.jsp";


            // perform discovery on the user-supplied identifier
            List<?> discoveries = manager.discover(openid);

            // attempt to associate with an OpenID provider
            // and retrieve one service endpoint for authentication
            DiscoveryInformation discovered = manager.associate(discoveries);

            // store the discovery information in the user's session
            session.setAttribute("openid-disco", discovered);

            // obtain a AuthRequest message to be sent to the OpenID provider
            AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

            // Attribute Exchange example: fetching the 'email' attribute
            //FetchRequest fetch = FetchRequest.createFetchRequest();
            //fetch.addAttribute("email",
                    // attribute alias
             //       "http://schema.openid.net/contact/email",   // type URI
             //       true);                                      // required

            // attach the extension to the authentication request
            //authReq.addExtension(fetch);

            if (! discovered.isVersion2() )
            {
                // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
                // The only method supported in OpenID 1.x
                // redirect-URL usually limited ~2048 bytes
                response.sendRedirect(authReq.getDestinationUrl(true));
            }
            else
            {
                // Option 2: HTML FORM Redirection
                // Allows payloads > 2048 bytes

                // <FORM action="OpenID Provider's service endpoint">
                // see samples/formredirection.jsp for a JSP example
                //authReq.getOPEndpoint();

                // build a HTML FORM with the message parameters
                //authReq.getParameterMap();


      out.write("\r\n");
      out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
      out.write("<head>\r\n");
      out.write("    <title>OpenID HTML FORM Redirection</title>\r\n");
      out.write("</head>\r\n");
      out.write("<!--<body onload=\"document.forms['openid-form-redirection'].submit();\">-->\r\n");
      out.write("<body>\r\n");
      out.write("    <form name=\"openid-form-redirection\" action=\"");
      out.print( authReq.getOPEndpoint() );
      out.write("\" method=\"post\" accept-charset=\"utf-8\">\r\n");

                Map pm=authReq.getParameterMap();
                Iterator keyit=pm.keySet().iterator();

                Object key;
                Object value;

                while (keyit.hasNext())
                {
                    key=keyit.next();
                    value=pm.get(key);
            
      out.write("\r\n");
      out.write("        <input type=\"hidden\" name=\"");
      out.print( key);
      out.write("\" value=\"");
      out.print( value);
      out.write("\"/>\r\n");
      out.write("        ");

                }
        
      out.write("\r\n");
      out.write("        <button type=\"submit\">Continue...</button>\r\n");
      out.write("    </form>\r\n");
      out.write("</body>\r\n");
      out.write("</html>\r\n");

            }
        }
        catch (OpenIDException e) {
            // present error to the user
            response.sendError(500);
        }

      out.write('\r');
      out.write('\n');
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
