/*
 * FlightDispatch.java	1.00 22-Feb-2001
 *
 * Copyright 2000-2001 by Oracle Corporation
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 */

package oracle.portal.sample.v1.devguide.partnerApp;

import java.io.*;
import java.util.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import oracle.portal.provider.v1.*;
import oracle.portal.provider.v1.http.*;

public class FlightDispatch
{

  private Vector mArgs = new Vector(3);

  private static final String ACTION      = "FlightAction";
  private static final String ID          = "FlightId";
  private static final String USERNAME    = "FlightUser";
  private static final String SHOWDETAILS = "details";
  private static final String FLIGHTDEST  = "FlightDest";

  private boolean mIsWebProvider = false;
  private PortletRenderRequest mPR = null;

 /**
  *  Constructor
  */
  public FlightDispatch()
  {
  }//FlightDispatch Constructor

 /**
  *  Parse a query string.
  *
  *  Parse the string passed, and build an array of arguments
  *  for future use.
  *
  *  @param queryString  in the form of an HTTP query.
  */
  private void parseQuery
  (
    String queryString,
    Vector args
  )
  {
    if (queryString == null)
    {
      return;
    }

    String name, value;
    int equal, stop, start = 0;

    while ((equal = queryString.indexOf('=', start)) != -1)
    {
      stop = queryString.indexOf('&', start);
      name = queryString.substring(start, equal);
      if (stop != -1)
      {
        value = queryString.substring(equal+1, stop);
        start = stop + 1;
      }
      else
      {
        value = queryString.substring(equal+1);
        start = queryString.length();
      }
      args.addElement(new String[] {name, value});
    }
  }//parseQuery

 /**
  *  Construct URLs for links to the detail screen.
  *
  *  Construct URLs based on weather or not we are running as
  *  as a web provider.
  *
  *  @param id  is the id number of the flight.
  *  @param localServer is the server string to use with the link.
  *
  *  @return the final link
  */
  private String buildURL(String id, String localServer)
  {
    StringBuffer server = new StringBuffer();
    server.append(localServer);
    String hrefValue = null;
    server.append("/servlets/flights?Flightaction=details&FlightId="+id);
    hrefValue = server.toString();

    return hrefValue;
  }


 /**
  *  Display the flight list screen.
  *
  *  @param user   The user who is logged in.
  *  @param server  present string representing the server.
  *  @param out  output writer for output.
  */
  private void showList(String user, StringBuffer server, Writer out)
    throws Exception
  {
    if (!mIsWebProvider)
    {
      out.write("<HTML>");
      out.write("<HEAD>");
      out.write("<TITLE>Filghts</TITLE></HEAD>");
      out.write("</HEAD>");
      out.write("<BODY>");
    }
    out.write("<font size=-2>Welcome "+user+"</font><br>");
    out.write("<CENTER>");
    out.write("<center><b><font color=\"#33CCFF\"><font size=+1>");
    out.write("Flights Of Fancy</font></font></b></center>");

    out.write("<br><b><font color=\"#3366FF\"></font></b>&nbsp;");
    out.write("<table BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=\"100%\" >");
    out.write("<tr>");
    out.write("<td><b><font color=\"#3333FF\">Flight Num</font></b></td>");
    out.write("<td><b><font color=\"#3333FF\">From</font></b></td>");
    out.write("<td><b><font color=\"#3333FF\">To</font></b></td>");
    out.write("<td><b><font color=\"#3333FF\">Departure</font></b></td>");
    out.write("<td><b><font color=\"#3333FF\">Arrival</font></b></td>");
    out.write("</tr>");
    out.write("<tr>");
    out.write("<TD><A href=\""+buildURL("123456",server.toString())+"\">");
    out.write("<font size=-1>123456</font></A></td>");
    out.write("<td><font size=-1>JFK</font></td>");
    out.write("<td><font size=-1>MIA</font></td>");
    out.write("<td><font size=-1>6:00 AM EST 12/12/2002</font></td>");
    out.write("<td><font size=-1>9:37 AM EST 12/12/2002</font></td>");
    out.write("</tr>");
    out.write("<tr>");
    out.write("<TD><A href=\""+buildURL("234567",server.toString())+"\">");
    out.write("<font size=-1>234567</font></A></td>");
    out.write("<td><font size=-1>IAD</font></td>");
    out.write("<td><font size=-1>BWI</font></td>");
    out.write("<td><font size=-1>5:00 PM EST 8/22/2002</font></td>");
    out.write("<td><font size=-1>6:45 PM EST 8/22/2002</font></td>");
    out.write("</tr>");
    out.write("<tr>");
    out.write("<td><A href=\""+buildURL("345678",server.toString())+"\">");
    out.write("<font size=-1>345678</font></A></td>");
    out.write("<td><font size=-1>SFI</font></td>");
    out.write("<td><font size=-1>NAT</font></td>");
    out.write("<td><font size=-1>1:25 PM PST 10/18/2002</font></td>");
    out.write("<td><font size=-1>4:37 AM EST 10/19/2002</font></td>");
    out.write("</tr>");
    out.write("<tr>");
    out.write("<td><A href=\""+buildURL("456789",server.toString())+"\">");
    out.write("<font size=-1>456789</font></A></td>");
    out.write("<td><font size=-1>OCH</font></td>");
    out.write("<td><font size=-1>DIA</font></td>");
    out.write("<td><font size=-1>10:00 PM CST 2/05/2002</font></td>");
    out.write("<td><font size=-1>2:11 AM CST 2/06/2002</font></td>");
    out.write("</tr>");
    out.write("</table>");
    out.write("<center><font color=\"#33CCFF\"><font size=-2>");
    out.write("All Times and flights are subject");
    out.write("to change without notification.&nbsp; Please consult our");
    out.write(" reservations center");
    out.write("for exact flights and times.</font></font></center>");
    if (!mIsWebProvider)
    {
      out.write("</BODY>");
      out.write("</HTML>");
    }
    else
    {
      out.write("</td></tr></table>");
    }
    out.flush();
    out.close();

  }//showList

 /**
  *  Display the details screen.
  *
  *  @param user   The user who is logged in.
  *  @param server  present string representing the server.
  *  @param out  output writer for output.
  *  @param id  id of the flight being displayed.
  */
  private void showDetails(String user, String id, String server, Writer out) throws Exception
  {
    out.write("<HTML>");
    out.write("<HEAD>");
    out.write("<TITLE>Flight "+ id+"</TITLE></HEAD>");
    out.write("</HEAD>");
    out.write("<BODY>");
    out.write("<font size=-2>Welcome "+user+"</font><br>");
    out.write("<center><b><font color=\"#33CCFF\"><font size=+1>");
    out.write("Flights Of Fancy</font></font></b></center>");
    out.write("<b><font color=\"#3333FF\">Details for "+id+"</font></b>");
    out.write("<br>");
    out.write("<hr WIDTH=\"100%\">");
    out.write("<br><font color=\"#000000\"><font size=-1>");
    out.write("Flight "+id+" operated by Fancy");
    out.write("Flying Airlines on a Wing Stream 77 Turbo Prop.</font></font>");
    out.write("<blockquote><font size=-1><font color=\"#000000\">");
    out.write("Departs:&nbsp;&nbsp; </font>6:00");
    out.write("AM EST 12/12/2002 From: JFK</font>");
    out.write("<br><font size=-1>Arrives:&nbsp; 9:37 AM EST 12/12/2002");
    out.write(" At: MIA</font>");
    out.write("<br><font size=-1>Stops:&nbsp; None</font>");
    out.write("<blockquote><font size=-1>Altitude:&nbsp; 35,000ft</font>");
    out.write("<br><font size=-1>Seating:&nbsp; Coach</font>");
    out.write("<br><font size=-1>Preferences:&nbsp; Exit Row</font>");
    out.write("<br><font size=-1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
    out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
    out.write("&nbsp;&nbsp;&nbsp;&nbsp;");
    out.write("Window</font>");
    out.write("<br><font size=-1>Smoking:&nbsp; No</font>");
    out.write("<br><font size=-1>Meals:&nbsp; ");
    out.write("Breakfast / Snack</font></blockquote>");
    out.write("<font size=-1>Price:&nbsp; $875</font></blockquote>");
    out.write("<hr WIDTH=\"100%\">");
    out.write("<center><font color=\"#33CCFF\"><font size=-2>");
    out.write("All Times and flights are subject");
    out.write("to change without notification.&nbsp; Please consult ");
    out.write("our reservations center");
    out.write("for exact flights and times.</font></font></center>");

    out.write("</BODY>");
    out.write("</HTML>");
    out.flush();
    out.close();
  }

 /**
  *  This method receives the requests, and makes the proper calls.
  *
  *  This is the main routine in the case of the standalone servlet.
  *  When direct servlet calls are made, they are processed here.  Based
  *  upon the parameters received, and the state of login, different screens
  *  are displayed.
  *
  *  @param req Servlet request object.
  *  @param res Servlet response object.
  */
  public void process
  (
    HttpServletRequest req,
    HttpServletResponse res
  )
  throws Exception
  {
    mPR = null;
    mIsWebProvider = false;
    boolean lBeingRedirected = false;
    String l_userInfo = null;

    if(req == null || res == null)
        {
             throw new ServletException("Http objects are null");
        }



    // Call getBakedUserInfo to check if the partner application cookie
    // has been set. If it has than the encrypted user name will be returned.
    // We do not want to call getSSOUserInfo since it will redirect to
    // the login if the cookie is not found and we still need to determine
    // if login information was passed by the login server on the HTTP req.
    l_userInfo = PartnerServlet.getSSOBean().getBakedUserInfo(req);

    if(l_userInfo == null)
    {
      res.setContentType("text/html");
      try
      {
        // The partner application cookie does not exist. However HTTP Req
        // may contain login information. Therefore, call the setPartnerAppCookie
        // setPartnerAppCookie will set the partner application cookie
        // when the request contains the login info, otherwise ir will
        // return null. The request will contain the login info when
        // the login server redirects to this routine after a sucessful
        // authentication.
        lBeingRedirected = PartnerServlet.getSSOBean().setPartnerAppCookie(req, res);
      }
      catch(Exception e)
      {
        try
        {
          res.getWriter().println("Error " + e.toString());
        }
        catch(Exception e1)
        {
          throw new ServletException(e1.toString());
        }
      }

      // Call getSSOUserInfo. getSSOUserInfo will check if the cookie was
      // created. If the cookie was created it will unbake the cookie and
      // return the user name. If the cookie was not created it will render
      // the redirect to the login server.
      // At this point no cookie was created and the HTTP req does not
      // contain the login info. Therefor call getSSOUserInfo to redirect
      // to the login server.
      if (! lBeingRedirected )
      {
        l_userInfo = PartnerServlet.getSSOBean().getSSOUserInfo(req, res);
      }
    } //endif username null
    else
    {
      // The cookie exists. Now get the unbaked user information by calling
      // getSSOUserInfo.
      l_userInfo = PartnerServlet.getSSOBean().getSSOUserInfo(req, res);
      res.setContentType("text/html");
      Writer out = res.getWriter();
      try
      {
        parseQuery(req.getQueryString(), mArgs);
        if (req.getMethod().equals("POST"))
        {

          //
          // ### Parse POSTed parameter stream here.
          //
          ServletInputStream stream = req.getInputStream();
          StringBuffer strBuf = new StringBuffer(100);
          byte[] buf = new byte[1024];
          int len;

          while ((len = stream.readLine(buf, 0, buf.length)) != -1)
          {
            strBuf.append(new String(buf, 0, len, "8859_1"));
          }

          parseQuery(strBuf.toString(), mArgs);
        }
        String[] argPair = null;
        String name = null;
        String username = null;
        String action = null;
        String id = null;
        String flightDest = null;
        //Pull out the needed parameters from the argument array.
        for(int i=mArgs.size()-1; i>=0;i--)
        {
          argPair = (String[])mArgs.elementAt(i);
          name = argPair[0];
          if (name.equalsIgnoreCase(ACTION))
          {
            action = argPair[1];
          }
          else if (name.equalsIgnoreCase(ID))
          {
            id = argPair[1];
          }
          else if (name.equalsIgnoreCase(USERNAME))
          {
            username = argPair[1];
          }
          else if (name.equalsIgnoreCase(FLIGHTDEST))
          {
            flightDest = argPair[1];
          }
        }
        String user = null;
        StringBuffer server = new StringBuffer();

        //Set up the server string to be passed around.
        server.append(req.getScheme()).append("://")
              .append(req.getServerName())
              .append(":")
              .append(req.getServerPort());

        //Call Show Details for logged in user
        if (action != null &&
            action.equalsIgnoreCase(SHOWDETAILS) &&
            id != null &&
            !id.equals(""))
        {
          server.append("/servlets/flights");
          showDetails(l_userInfo,id,server.toString(),res.getWriter());
        }
        else
        {
          showList(l_userInfo,server,res.getWriter());
        }
      } // end try
      catch (Exception e)
      {
        throw e;
      }
    } // end else
  }

 /**
  *  This method receives the requests, and makes the proper calls.
  *
  *  This is the main routine in the case of the provider impementation.
  *  When calls from portal are made, they are processed here.  Based
  *  upon the parameters received, and the state of login, different screens
  *  are displayed.
  *
  *  @param pr Render request object
  */
  public void process
  (
    PortletRenderRequest pr
  )
  throws Exception
  {
    mPR = pr;
    mIsWebProvider = true;
    String l_userInfo = null;

    try
    {
      // Call getPartnerAppCookie to check if the partner application cookie
      // has been set. If it has than the unencrypted user name will be returned.
      // If the cookie is not found and the http request contains a value for
      // urlc, then the partner application cookie will be set and the user name
      // will be returned. Otherwise, null will be returned.
      l_userInfo = PartnerProvider.getSSOBean().getSSOUserInfo(
        (HttpServletRequest)  pr.getAttribute(HttpProvider.SERVLET_REQUEST));

      //Begin processing by checking the login status.
      if (l_userInfo != null)
      {
        Enumeration argNames = pr.getAttributeNames();
        String name = null;
        String username = null;
        String action = null;
        String id = null;
        //Pull out the needed parameters from the argument array.
        while(argNames.hasMoreElements())
        {
          name = (String)argNames.nextElement();
          if (name.equalsIgnoreCase(ACTION))
          {
            action = (String)pr.getAttribute(name);
          }
          else if (name.equalsIgnoreCase(ID))
          {
            id = (String)pr.getAttribute(name);
          }
          else if (name.equalsIgnoreCase(USERNAME))
          {
            username = (String)pr.getAttribute(name);
          }
        }
        String user = pr.getUser().getName();
        StringBuffer server = new StringBuffer();
        server.append(pr.getScheme()).append("://")
              .append(pr.getServerName())
              .append(":")
              .append(pr.getServerPort());


        showList(l_userInfo, server, pr.getWriter("text/html"));
      }//if loggedin
      else
      {
           throw new ServletException("User is not authenticated.");
      }
    }
    catch (Exception e)
    {
      throw e;
    }
  }

}//FlightDispatch
