/*
 * FlightDispatch.java 1.00 27-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.externalApp;

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

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 PASSWORD = "FlightPass";
  private static final String SHOWDETAILS = "details";
  private static final String PERFORMLOGIN = "performlogin";
  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;
    if (mIsWebProvider)
    {
      String loginURL=mPR.getLoginServerURL();
      PortletRendererUtil pru = new PortletRendererUtil();
      String str1 = pru.parameterizeLink(loginURL,"p_url_name=FlightDest");

      server.append("/servlets/flights?Flightaction=details&FlightId="+id);
      hrefValue = pru.parameterizeLink(str1,
        "p_url_value="+URLEncoder.encode(server.toString()));
    }
    else
    {
      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>Flights</TITLE></HEAD>");
      out.write("<BODY>");
    }
    out.write("<table BORDER=1 WIDTH=\"100%\" ><tr><td>");
    out.write("<font size=-1>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>");
    out.write("</td></tr></table>");
    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("<BODY>");
    out.write("<font size=-1>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;
    ApplicationLogin login = new ApplicationLogin(req,res);
    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 password = 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(PASSWORD))
        {
          password = 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());
      int serverPort = req.getServerPort();

      // set the content type to html
      res.setContentType("text/html");
      // If it's the defualt port, don't append the port
      // number
      if (( serverPort != 80) && (serverPort!= 433))
      {
          server.append(":")
                .append(serverPort);
      }

      //Begin processing by checking the login status.
      if (login.isLoggedIn())
      {
        user = login.getUser();
        if (action != null &&
            action.equalsIgnoreCase(SHOWDETAILS) &&
            id != null &&
            !id.equals(""))
        {
          server.append("/servlets/flights");
          showDetails(user,id,server.toString(),res.getWriter());
        }
        else if (action != null &&
                 action.equalsIgnoreCase(PERFORMLOGIN) &&
                 username != null && password != null)
        {
          if (flightDest == null)
          {
            flightDest = server.toString() + "/servlets/flights";
            login.performLogin(username,password,flightDest);
          }
          else
          {
            login.performLogin(username,
                               password,
                               MultiByteDecoder.decode(flightDest, "iso8859-1"));
          }
        }
        else
          showList(user,server,res.getWriter());
      }//if loggedin
      else
      {
        if (action != null &&
            action.equalsIgnoreCase(PERFORMLOGIN))
        {
          if (flightDest == null)
          {
            flightDest = server.toString() + "/servlets/flights";
            login.performLogin(username,password,flightDest);
          }
          else
          {
            login.performLogin(username,
                               password,
                               MultiByteDecoder.decode(flightDest, "iso8859-1"));
          }
        }
        else
        {
          login.drawLogin();
        }
      }
    }
    catch (Exception e)
    {
      throw e;
    }
  }

 /**
  *  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;
    ApplicationLogin login = new ApplicationLogin(pr);
    try
    {
      Enumeration argNames = pr.getAttributeNames();
      String name = null;
      String username = null;
      String password = null;
      String action = null;
      String id = null;
      Writer out = pr.getWriter("text/html");

      // print snoop information
/*
      out.write("<table BORDER=1 WIDTH=\"100%\" ><tr><td>");
      out.write("<tr><td>");
      out.write("<B><font color=\"#3333FF\" size = -1>Session Data:</font></B>");
      out.write("<BR><font size = -1>");
      String[] temp = pr.getParameterValues("_user");
      if (temp != null)
        out.write("<B>UserId:&nbsp;&nbsp;</B>"+temp[0]+"<BR>");
      else
        out.write ("<B>UserID</B>  is null<BR>");
      temp = pr.getParameterValues("_sessionid");
      if (temp != null)
        out.write("<B>SessionId:&nbsp;&nbsp;</B>"+temp[0]+"<BR>");
      else
        out.write("<B>SessionID</B>  is null<BR>");
      temp = pr.getParameterValues("_mapped_user");
      if (temp != null)
        out.write("<B>Mapped User:&nbsp;&nbsp;</B>"+temp[0]+"<BR>");
      else
        out.write ("<B>Mapped User</B>  is null<BR>");
      temp = pr.getParameterValues("_logintime");
      if (temp != null)
        out.write("<B>Login Time:&nbsp;&nbsp;</B>"+temp[0]+"<BR>");
      else
        out.write ("<B>Login Time</B>  is null<BR>");
      out.write("</font>");
      out.write("</tr></td>");
      out.write("<tr><td>");
      out.write("<B><font size = -1 color=\"#3333FF\">Cookies:</font></B>");
      out.write("<BR><font size = -1>");
      Cookie[] cookieList = (Cookie[])pr.getCookies();
      for ( int i= cookieList.length-1; i >= 0 ; i-- )
      {
       out.write("<B>" + cookieList[i].getName()+"</B> = "+cookieList[i].getValue() );
       out.write("<br>");
      }
      out.write("</font></tr></td>");
      out.write("<tr><td>");
      out.write("<B><font size = -1 color=\"#3333FF\">Other Parameters:</font></B>");
      out.write("<BR>");

      java.util.Enumeration names = pr.getParameterNames();
      while (names != null && names.hasMoreElements())
      {
        String paramName = (String) names.nextElement();
        out.write("<font size = -2><B>" + paramName+":</B>");
        String[] values = pr.getParameterValues(paramName);
        if (values != null)
        {
            String outStr = " ";
            for (int j = 0; j < values.length; j++)
            {
                outStr = outStr + values[j] + ", ";
            }
            out.write(outStr.substring(0, outStr.length() - 2) + " <br>");
        }
      }
      out.write("</font>");
      out.write("</tr></td>");
      out.write("</table>");
*/
      String user = pr.getUser().getName();
      StringBuffer server = new StringBuffer();
      server.append(pr.getScheme()).append("://")
            .append(pr.getServerName());
      int serverPort = pr.getServerPort();

      if (( serverPort != 80) && (serverPort!= 433))
      {
          server.append(":")
                .append(serverPort);
      }
      if (login.isLoggedIn())
      {
        user = login.getUser();
        showList(user, server, out);
      }//if loggedin

    }
    catch (Exception e)
    {
      throw e;
    }
  }

}//FlightDispatch
