Package HTTP

Source Code of HTTP.HTTPAccess

/*
Copyright (c) 2003-2009 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package HTTP;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import Framework.BinaryData;
import Framework.DistributedAccessException;
import Framework.DynamicArray;
import Framework.ErrorMgr;
import Framework.ExternalConnection;
import Framework.GenericException;
import Framework.IntervalData;
import Framework.ParameterHolder;
import Framework.ParameterHolder_NamedElement_Array;
import Framework.ParameterHolder_Object;
import Framework.Stream;
import Framework.TextData;
/**
* The HTTPAccess class defines a number of characteristics of a UDS web access service object.
* The Web access service is the primary link between a Web browser and the application; its primary responsibility is to respond to an HTTP request from the Web client by returning the appropriate Web page.
* A corresponding servlet is generated for each access server
*/
public class HTTPAccess
implements PropertyChangeListener, IHTTPAccess
{
  private static final Logger webentLogger = Logger.getLogger("WebEnt");
  /**
   * Get a logger used for web enterprise logging. This logger is associated with the "WebEnt" logger in log4j.
   * @return
   */
  public static Logger getWebEntLogger() {
    return webentLogger;
  }
 
    public HTTPAccess() {
        this.autoReg = false;
        this.serviceName = null;
        this.applicationName = null;
        this.CGIURL = null;
        this.execURL = null;
        this.pluginURL = null;
        this.usePluginURL = false;
        this.sessionProperty = HTTPAccess.SESSION_UNSPECIFIED;
        this.sessionPropertyTable = null;
        this.sessionPropertyConfigFile = null;
        this.webEntSessionConfigFileLastReadDt = null;
        this.sessionMgmtEnabled = false;
        //this.cmdLineRead = false;
        //this.WebEntTimeoutArray = new DynamicArray(/*WebEntTimeoutData.class*/ );
        //this.WebEntResponseTimeout = new IntervalData(00,00,00,00,00,00,00);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#deregistration(boolean)
   */
    public boolean deregistration(boolean all) {
        throw new UnsupportedOperationException(
                "HTTPAccess.deregistration() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#dumpStatus(Framework.Stream)
   */
    public void dumpStatus(Stream ostream) {
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.dumpStatus() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;

    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getErrorTemplate(Framework.GenericException, javax.servlet.http.HttpServletRequest, Framework.ParameterHolder_NamedElement_Array)
   */
    public TextData getErrorTemplate(GenericException e,
            HttpServletRequest request,
            ParameterHolder_NamedElement_Array customParameters) {
        throw new UnsupportedOperationException(
        "HTTPAccess.getErrorTemplate() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#handleRequest(javax.servlet.http.HttpServletRequest)
   */
    public HttpServletResponse handleRequest(HttpServletRequest request) {
        throw new UnsupportedOperationException(
        "HTTPAccess.handleRequest() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#handleTemplateRequest(javax.servlet.http.HttpServletRequest)
   */
    public HttpServletResponse handleTemplateRequest(HttpServletRequest request)
    throws DistributedAccessException {
        throw new UnsupportedOperationException(
        "HTTPAccess.handleTemplateRequest() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#listenTask(int)
   */
    public void listenTask(int servicePort) {
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.listenTask() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;

    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#printSessionPropertyTable()
   */
    public TextData printSessionPropertyTable() {
        throw new UnsupportedOperationException(
        "HTTPAccess.printSessionPropertyTable() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#processConnection(Framework.TextData, Framework.ExternalConnection)
   */
    public void processConnection(TextData applicationName,
            ExternalConnection newConnection) {
        throw new UnsupportedOperationException(
        "HTTPAccess.processConnection() is not implemented");

    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#processException2(Framework.ExternalConnection, Framework.GenericException)
   */
    public void processException2(ExternalConnection newConnection,
            GenericException ex) {
        throw new UnsupportedOperationException(
        "HTTPAccess.processException2() is not implemented");

    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#registration(int)
   */
    public boolean registration(int servicePort) {
        throw new UnsupportedOperationException(
        "HTTPAccess.registration() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#showException(Framework.GenericException)
   */
    public HttpServletResponse showException(GenericException ex) {
        throw new UnsupportedOperationException(
        "HTTPAccess.showException() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#updateFromSessionConfigFile()
   */
    public void updateFromSessionConfigFile() {
        throw new UnsupportedOperationException(
        "HTTPAccess.updateFromSessionConfigFile() is not implemented");

    }

    public void write16k(BinaryData body, ExternalConnection newConnection) {
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.write16k() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;

    }

    public void write16k(TextData sendData, ExternalConnection newConnection) {
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.write16k() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;

    }

    private boolean autoReg;
    private String CGIURL;
    private String execURL;
    private String pluginURL;
    private String applicationName;
    //private boolean CmdLineConfigFile;
    //private boolean CmdLineDocRoot;
    //private boolean cmdLineRead;
    private String webEntdocroot;
    private String webEntEncryptKey;
    private Date webEntSessionConfigFileLastReadDt;
    private boolean sessionMgmtEnabled;
    private DynamicArray<PathSessionProperty> sessionPropertyTable;  // Array of WebEntPathSessionProperty
    private String serviceName;
    private String sessionCreationURL;
    private int sessionProperty;
    private String sessionPropertyConfigFile;
    private boolean usePluginURL;
    //private DynamicArray WebEntTimeoutArray;  // Array of WebEntTimeoutData
    //private IntervalData WebEntResponseTimeout;
    private int maxThreadsAllowed;
    //private long sessionTimeout = 1800; // SW | Aug-2007 | MT#841 | Used to be -1 (never timeout)
                                        // contrary to FORTE help, which suggests the default is 30 (mins)
                                        // this value is in seconds (=30*60)
    private SessionMgr webSessionMgr = new SessionMgr(this);
    private Cookie defaultCookie = null;
    private int httpSocketCloseDelay = 0;
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getHTTPSocketCloseDelay()
   */
    public int getHTTPSocketCloseDelay() {
        return httpSocketCloseDelay;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setHTTPSocketCloseDelay(int)
   */
    public void setHTTPSocketCloseDelay(int socketCloseDelay) {
        httpSocketCloseDelay = socketCloseDelay;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setMaxThreadsAllowed(int)
   */
    public void setMaxThreadsAllowed(int maxThreadsAllowed) {
        this.maxThreadsAllowed = maxThreadsAllowed;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setPluginURL(java.lang.String)
   */
    public void setPluginURL(String pluginURL) {
        this.pluginURL = pluginURL;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getWebSessionMgr()
   */
    public SessionMgr getWebSessionMgr() {
        return webSessionMgr;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setWebSessionMgr(HTTP.SessionMgr)
   */
    public void setWebSessionMgr(SessionMgr webSessionMgr) {
        this.webSessionMgr = webSessionMgr;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setAutoReg(boolean)
   */
    public void setAutoReg(boolean pValue) {
        this.autoReg = pValue;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getAutoReg()
   */
    public boolean getAutoReg() {
        return this.autoReg;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setCGIURL(java.lang.String)
   */
    public void setCGIURL(String pValue) {
        this.CGIURL = pValue;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setCGIURL(Framework.TextData)
   */
    public void setCGIURL(TextData pValue) {
        this.CGIURL = pValue.toString();
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getCGIURL()
   */
    public TextData getCGIURL() {
        return new TextData(this.CGIURL);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getExecURL()
   */
    public TextData getExecURL() {
        return new TextData(this.execURL);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getListener()
   */
    public ExternalConnection getListener(){
        throw new UnsupportedOperationException(
                "HTTPAccess.getListener() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setListener(Framework.ExternalConnection)
   */
    public void setListener(ExternalConnection conn){
        throw new UnsupportedOperationException(
                "HTTPAccess.setListener() is not implemented");
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getPluginURL()
   */
    public TextData getPluginURL() {
        return new TextData(this.pluginURL);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setApplicationName(java.lang.String)
   */
    public void setApplicationName(String pValue) {
        this.applicationName = pValue;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getWebEntdocroot()
   */
    public String getWebEntdocroot() {
        return this.webEntdocroot;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getWebEntEncryptKey()
   */
    public String getWebEntEncryptKey() {
        return this.webEntEncryptKey;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getWebEntSessionConfigFileLastReadDt()
   */
    public Date getWebEntSessionConfigFileLastReadDt() {
        return this.webEntSessionConfigFileLastReadDt;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setServiceName(java.lang.String)
   */
    public void setServiceName(String pValue) {
        this.serviceName = pValue;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setServiceName(Framework.TextData)
   */
    public void setServiceName(TextData pValue) {
        setServiceName(pValue.toString());
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getServiceName()
   */
    public TextData getServiceName() {
        return new TextData(this.serviceName);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionCreationURL(java.lang.String)
   */
    public void setSessionCreationURL(String pValue) {
        this.sessionCreationURL = pValue;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionCreationURL(Framework.TextData)
   */
    public void setSessionCreationURL(TextData pValue) {
        this.sessionCreationURL = pValue.toString();
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getSessionCreationURL()
   */
    public TextData getSessionCreationURL() {
        return new TextData(this.sessionCreationURL);
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setUsePluginURL(boolean)
   */
    public void setUsePluginURL(boolean value){
        throw new UnsupportedOperationException(
                "HTTPAccess.setUsePluginURL() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setUseLBF(boolean)
   */
    public void setUseLBF(boolean value){
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.setUseLBF() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getUseLBF()
   */
    public boolean getUseLBF(){
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.getUseLBF() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionFailoverURL(Framework.TextData)
   */
    public void setSessionFailoverURL(TextData url){
        throw new UnsupportedOperationException(
        "HTTPAccess.setSessionFailoverURL() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getSessionFailoverURL()
   */
    public TextData getSessionFailoverURL(){
        throw new UnsupportedOperationException(
        "HTTPAccess.getSessionFailoverURL() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setRegistrationDelay(int)
   */
    public void setRegistrationDelay(int delay){
        throw new UnsupportedOperationException(
        "HTTPAccess.setRegistrationDelay() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getRegistrationDelay()
   */
    public int getRegistrationDelay(){
        throw new UnsupportedOperationException(
        "HTTPAccess.getRegistrationDelay() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionProperty(int)
   */
    public void setSessionProperty(int pValue) {
        this.sessionProperty = pValue;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getResponseTimeout()
   */
    public int getResponseTimeout(){
        throw new UnsupportedOperationException(
                "HTTPAccess.getResponseTimeout() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setMaxThreadsPersistentAllowed(int)
   */
    public void setMaxThreadsPersistentAllowed(int value){
        throw new UnsupportedOperationException(
        "HTTPAccess.setMaxThreadsPersistentAllowed() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getMaxThreadsPersistentAllowed()
   */
    public int getMaxThreadsPersistentAllowed(){
        throw new UnsupportedOperationException(
        "HTTPAccess.getMaxThreadsPersistentAllowed() is not implemented");
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getSessionProperty()
   */
    public int getSessionProperty() {
        return this.sessionProperty;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionPropertyConfigFile(java.lang.String)
   */
    public void setSessionPropertyConfigFile(String pValue) {
        this.sessionPropertyConfigFile = pValue;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getSessionPropertyConfigFile()
   */
    public TextData getSessionPropertyConfigFile() {
        return new TextData(this.sessionPropertyConfigFile);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getUsePluginURL()
   */
    public boolean getUsePluginURL() {
        return this.usePluginURL;
    }


    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getMaxThreadsAllowed()
   */
    public int getMaxThreadsAllowed() {
        return this.maxThreadsAllowed;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#disableAccess()
   */
    public void disableAccess() throws HTTPAccessException {
        this.execURL = null;
        this.pluginURL = null;
        this.usePluginURL = false;

        this.CGIURL = null;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#disableSessionManagement()
   */
    public void disableSessionManagement() {
        this.sessionMgmtEnabled = false;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#enableAccess(Framework.TextData, int)
   */
    public void enableAccess(TextData serviceName, int servicePort) throws HTTPAccessException {
        enableAccess(serviceName.toString(),servicePort, null, null);
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#enableAccess(Framework.TextData, int, Framework.TextData)
   */
    public void enableAccess(TextData serviceName, int servicePort, TextData URLForForteCGI) throws HTTPAccessException {
        enableAccess(serviceName.toString(),servicePort,URLForForteCGI.toString(), null);
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#enableAccess(Framework.TextData, int, Framework.TextData, Framework.TextData)
   */
    public void enableAccess(TextData serviceName, int servicePort, TextData URLForForteCGI, TextData pluginURL)
    throws HTTPAccessException {
        enableAccess(serviceName.toString(),servicePort,URLForForteCGI.toString(), pluginURL.toString());
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#enableAccess(java.lang.String, int, java.lang.String, java.lang.String)
   */
    public void enableAccess(String serviceName, int servicePort, String URLForForteCGI, String pluginURL)
    throws HTTPAccessException
    {
        if (serviceName == null) {
            HTTPAccessException ex = new HTTPAccessException("serviceName is unknown." );
            ex.setDetectingMethod("HTTPAccess::EnableAccess");
            throw ex;
        }
        else {
            this.serviceName = serviceName;
            this.applicationName = serviceName;
        }

        if (HTTPAccess.getWebEntLogger().isDebugEnabled()) {
          HTTPAccess.getWebEntLogger().debug("Web Service " + serviceName + " will use " + this.applicationName + " as cookie name");
        }

        if (URLForForteCGI != null) {
            this.autoReg = true;
            this.CGIURL = URLForForteCGI;
            this.execURL = URLForForteCGI;
        }
        else {

            if (this.execURL == null) {
                HTTPAccessException ex = new HTTPAccessException("HTTPAccess.ExecURL must be initialized using the SetExecURL method." );
                ex.setDetectingMethod("HTTPAccess::EnableAccess");
                throw ex;
            }
            this.autoReg = false;

        }


    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#enableSessionManagement()
   */
    public void enableSessionManagement() {
        this.setSessionProperty(new TextData("/"), this.sessionProperty);
        this.sessionMgmtEnabled = true;
    }

    protected String getPageName(HttpServletRequest request) {
        return request.getParameterValues("PageName")[0];
    }
   
    protected String getTemplateName(HttpServletRequest request) {
        return request.getParameterValues("TemplateName")[0];
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
    public HttpServletResponse handleRequest(HttpServletRequest request, HttpServletResponse response)
    throws HTTPAccessException
    {
        TextData pageName = new TextData();

        pageName.setValue( request.getParameterValues("PageName").toString() );

        if (pageName.isEqual("EnterNewPageNameHere", true).getValue()) {
        }
        else {
            Object[] qq_Args = { pageName };
            HTTPAccessException ex = new HTTPAccessException(MessageFormat.format( "Unknown PageName: {0}.", qq_Args ) );
            ex.setDetectingMethod("HTTPAccess::HandleRequest");
            throw ex;

        }
        return response;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#handleTemplateRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
    public HttpServletResponse handleTemplateRequest(HttpServletRequest request, HttpServletResponse response) {
        GenericException e = new GenericException("handleTemplateRequest() Needs to be overridden" );
        ErrorMgr.addError(e);
        throw e;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#logonSession(javax.servlet.http.HttpServletRequest, Framework.ParameterHolder_Object)
   */
    public boolean logonSession(HttpServletRequest request, ParameterHolder_Object credentials) {
        return this.logonSession(request, credentials);
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#logonSession(javax.servlet.http.HttpServletRequest, Framework.ParameterHolder)
   */
    public boolean logonSession(HttpServletRequest request, ParameterHolder credentials)
    {
        //  Should be overriden to validate Session logons.
        //
        //  Default logon pages will return:
        //   userName : TextData = request.FindNameValue('Username');
        //   passWord : TextData = request.FindNameValue('Password');
        //
        //  The "credentials" object may be used to return authentication
        //  data which can be attached to the session.
        //
        //  Return values:
        //   TRUE  - logon validated; session may be created.
        //   FALSE - login rejected.
        //
        throw new UnsupportedOperationException("HTTPAccess.logonSession() is not implemented");
    }


    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#sendRequest(Framework.TextData, java.lang.String)
   */
    public HttpServletResponse sendRequest(TextData request, String requestMethod)
    throws HTTPAccessException //, RemoteException
    {
//    HttpServletRequest newRequest = new HttpServletRequestWrapper();
//    newRequest.setURI(request.getValue());
//    newRequest.setRequestMethod(requestMethod);
//    return this.sendRequest(newRequest);
        throw new UnsupportedOperationException("HTTPAccess.sendRequest() is not implemented");
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#sendRequest(java.lang.String, java.lang.String)
   */
    public HttpServletResponse sendRequest(String request, String requestMethod)
    throws HTTPAccessException//, RemoteException
    {
//    HttpServletRequest newRequest = new HttpServletRequest();
//    newRequest.setURI(request);
//    newRequest.setRequestMethod(requestMethod);
//    return this.sendRequest(newRequest);
        throw new UnsupportedOperationException("HTTPAccess.sendRequest() is not implemented");
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#sendRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
    public HttpServletResponse sendRequest(HttpServletRequest request, HttpServletResponse response)
    throws /*RemoteException,*/ HTTPAccessException
    {
//    try {
//    //  This method will send an HttpServletRequest to the Web server and
//    //  return the response from the Web.
//    HttpServletResponse response = new HttpServletResponse();
//    int addressType = 0;
//    int port = 0;
//    TextData url = new TextData(request.getURI());
//    TextData body = new TextData();
//    boolean serverConnected = false;

//    //  Make sure the URL doesn't have any wacky characters

//    if ((url.moveToChar("\r") == true) || (url.moveToChar("\n") == true)) {
//    HTTPAccessException ex = null;
//    throw new HTTPAccessException("URL may not contain CRLF character(s)." );

//    //  Skip 'http://' at the beginning of URL.
//    }
//    url.setOffset(0);

//    //  Web server address is used in making connection.
//    //  It has two formats: IP address or Domain name address.
//    url.moveToString("http://", true);
//    int startIndex = url.getOffset();
//    TextData servertd = new TextData();
//    TextData requesttd = new TextData();
//    TextData serverAddress = new TextData();

//    //  If server address begins with digit, it is IP address.

//    if (url.isDigit()) {
//    addressType = Framework.Constants.CM_ADDR_INTERNET_DOT;
//    }
//    else {
//    addressType = Framework.Constants.CM_ADDR_INTERNET_NAME;

//    //  Separate the server name and the rest of the URL.
//    //  Once we have a connection with the server, we will only
//    //  send the rest of the URL.
//    }

//    if (url.moveToChar("/")) {
//    servertd = url.copyRange(startIndex, url.getOffset());
//    requesttd = url.copyRange(url.getOffset());
//    }
//    else {
//    servertd = url.copyRange(startIndex);
//    // Default request is getting the root index file.
//    requesttd.setValue( "/" );

//    //  Get server address and port number if ':' is found.
//    }

//    if (servertd.moveToChar(":")) {
//    serverAddress = servertd.copyRange(0, servertd.getOffset());
//    servertd.moveNext();
//    port = servertd.copyRange(servertd.getOffset()).getIntegerValue();
//    }
//    else {
//    //  Default port for Web server.
//    port = 80;
//    serverAddress = servertd;

//    //  Construct the actual data being sent.
//    }

//    if (request.getRequestMethod() == null) {
//    //  Default method is GET.
//    request.setRequestMethod("GET");
//    }
//    TextData sendData = new TextData(request.getRequestMethod());
//    sendData.toUpper();
//    sendData.concat(" ");
//    sendData.concat(requesttd);

//    //  Append request headers.  We support HTTP 1.0, so the header
//    //  fields we use here are standard HTTP/1.0 header fields.
//    sendData.concat(" HTTP/1.0\r\n");

//    if (request.getDate() != null) {
//    sendData.concat("Date: ").concat(request.getDate()).concat("\r\n");
//    }

//    if (request.getMIMEVersion() != null) {
//    sendData.concat("MIME-Version: ").concat(request.getMIMEVersion()).concat("\r\n");
//    }

//    if (request.getPragma() != null) {
//    sendData.concat("Pragma: ").concat(request.getPragma()).concat("\r\n");
//    }

//    if (request.getAuthorization() != null) {
//    sendData.concat("Authorization: ").concat(request.getAuthorization()).concat("\r\n");
//    }

//    if (request.getRequestFrom() != null) {
//    sendData.concat("From: ").concat(request.getRequestFrom()).concat("\r\n");
//    }

//    if (request.getIfModifiedSince() != null) {
//    sendData.concat("If-Modified-Since: ").concat(request.getIfModifiedSince()).concat("\r\n");
//    }

//    if (request.getReferer() != null) {
//    sendData.concat("Referer: ").concat(request.getReferer()).concat("\r\n");
//    }

//    if (request.getUserAgent() != null) {
//    sendData.concat("User-Agent: ").concat(request.getUserAgent()).concat("\r\n");
//    }

//    if (request.getAllow() != null) {
//    sendData.concat("Allow: ").concat(request.getAllow()).concat("\r\n");
//    }

//    if (request.getContentEncoding() != null) {
//    sendData.concat("Content-Encoding: ").concat(request.getContentEncoding()).concat("\r\n");
//    }

//    if ((boolean)(request.getContentLength() != 0)) {
//    sendData.concat("Content-Length: ").concat(request.getContentLength()).concat("\r\n");
//    }

//    if (request.getExpires() != null) {
//    sendData.concat("Expires: ").concat(request.getExpires()).concat("\r\n");
//    }

//    if (request.getContentType() != null) {
//    sendData.concat("Content-Type: ").concat(request.getContentType()).concat("\r\n");
//    }

//    if (request.getLastModified() != null) {
//    sendData.concat("Last-Modified: ").concat(request.getLastModified()).concat("\r\n");
//    }

//    if ((boolean)(request.getCookieParameters().getItems() > 0)) {
//    sendData.concat("Cookie:");
//    boolean firstOne = true;
//    DynamicArray qq_localVector = request.getCookieParameters();
//    for (Iterator qq_it = qq_localVector.iterator(); qq_it.hasNext();) {
//    NamedElement row = (NamedElement)qq_it.next();

//    if (!(firstOne)) {
//    sendData.concat(";");
//    }
//    sendData.concat(" ").concat(row.getName());
//    sendData.concat("=").concat(((TextData)row.getObject()));
//    firstOne = false;
//    }
//    sendData.concat("\r\n");

//    //  Append an extra CRLF to the end.
//    }
//    //  Append the Entity-Body if any.
//    sendData.concat("\r\n");

//    //  Setup buffer for sendData.
//    sendData.concat(request.getEntityBody());
//    sendData.setOffset(0);
//    int length = sendData.lengthToEnd();
//    MemoryStream buf = new MemoryStream();
//    buf.open(Framework.Constants.SP_AM_READ_WRITE);
//    buf.seek(0);


//    buf.writeText(sendData);
//    HTTPAccess.getWebEntLogger().info(Framework.Constants.SP_MT_DEBUG );


//    //  Connect to Web server.
//    HTTPAccess.getWebEntLogger().info(Framework.Constants.SP_MT_DEBUG );
//    ExternalConnection conn = new ExternalConnection();

//    //  After we connect to the server, set serverConnected
//    //  to TRUE so that when handling RemoteAccessException, we know
//    //  it is a read problem or a write problem.
//    conn.open(serverAddress, port, null, addressType);

//    //  Write the request line into the socket.
//    serverConnected = true;

//    //  Get the response from the socket.
//    // ----------------------------
//    // Parameters for call to Write
//    // ----------------------------
//    ParameterHolder qq_writeLength = new ParameterHolder(length);
//    conn.write(buf, qq_writeLength);
//    length = qq_writeLength.getInt();
//    body = new TextData();
//    TextData td = new TextData();
//    try {
//    while (true) {
//    buf.seek(0);
//    length = 16384;
//    // ---------------------------
//    // Parameters for call to Read
//    // ---------------------------
//    ParameterHolder qq_readLength = new ParameterHolder(length);
//    conn.read(buf, qq_readLength);
//    length = qq_readLength.getInt();
//    //   task.lgr.put('Response buffer: ');
//    //   task.lgr.putline(td);
//    buf.readText(td, length);
//    body.concat(td);

//    }
//    }
//    catch (RemoteAccessException e) {
//    conn.close();
//    break;
//    }
//    HTTPAccess.getWebEntLogger().info(Framework.Constants.SP_MT_DEBUG );

//    //  Assign the return data from the socket to the
//    //  variable "response".
//    HTTPAccess.getWebEntLogger().info(Framework.Constants.SP_MT_DEBUG );

//    response.assignResponse(body);

//    return response;
//    }
//    catch (RemoteAccessException ex) {
//    conn.close();

//    if (serverConnected) {
//    throw ex;
//    }
//    else {
//    TextData td = new TextData();
//    td.concat("SystemResourceException: Unable to locate the server.");
//    response.assignResponse(td);
//    }
//    return response;
//    }
//    catch (SystemResourceException ex) {
//    TextData td = new TextData();
//    td.concat("SystemResourceException: Unable to locate the server.");
//    response.assignResponse(td);
//    return response;
//    }
        throw new UnsupportedOperationException("HTTPAccess.sendRequest() is not implemented");
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setDefaultSessionProperty(int)
   */
    public void setDefaultSessionProperty(int newSessionProperty) {
        if ((SESSION_REQUIRED < newSessionProperty) ||
                (newSessionProperty < SESSION_UNSPECIFIED)){
            GenericException errorVar = new GenericException("Invalid Session Property");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        this.sessionProperty = newSessionProperty;
        this.setSessionProperty(new TextData("/"), newSessionProperty);
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setEncryptKey(Framework.TextData)
   */
    public void setEncryptKey(TextData NewKey) {
//    throw new UnsupportedOperationException(
//    "HTTPAccess.setEncryptKey() is not implemented");
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setExecURL(java.lang.String)
   */
    public void setExecURL(String url) {
        this.execURL = url;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setExecURL(Framework.TextData)
   */
    public void setExecURL(TextData url){
        setExecURL(url.toString());
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setPluginURL(Framework.TextData)
   */
    public void setPluginURL(TextData url) {
        this.pluginURL = url.toString();
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionProperty(Framework.TextData, int)
   */
    public void setSessionProperty(TextData pathName, int sessionProperty)
    {
        if ((HTTPAccess.SESSION_REQUIRED < sessionProperty)||
                (sessionProperty < HTTPAccess.SESSION_UNSPECIFIED)){
            GenericException errorVar = new GenericException("Invalid Session Property");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        if (pathName.getAllocatedSize() >= 1){
            String beginChar= pathName.toString().substring(0, 1);
            if (!beginChar.equals("/")){
                String newDirName = "/" + pathName.toString();
                pathName.setValue(newDirName);
            }
            String path = pathName.toString();
            String endChar = path.substring(path.length()-1);
            if (!endChar.equals("/")){
                pathName.concat("/");
            }
        }

        PathSessionProperty newDP = new PathSessionProperty(pathName.toString(), sessionProperty);

        if (this.sessionPropertyTable == null){
            this.sessionPropertyTable = new DynamicArray<PathSessionProperty>(PathSessionProperty.class);
            this.sessionPropertyTable.add(newDP);
        } else {
            boolean dirInserted = false;
            int currRow = 0;
            Iterator<PathSessionProperty> it = this.sessionPropertyTable.iterator();
            while (it.hasNext()){
                PathSessionProperty aDirProp = it.next();
                if (aDirProp.getPathName().length() < newDP.getPathName().length()){
                    this.sessionPropertyTable.add(currRow, newDP);
                    dirInserted = true;
                    break;
                } else if (aDirProp.getPathName().length() == newDP.getPathName().length()){
                    if (aDirProp.getPathName().equals(newDP.getPathName())) {
                        if (aDirProp.getSessionProperty() != newDP.getSessionProperty()){
                            aDirProp.setSessionProperty(newDP.getSessionProperty());
                            dirInserted = true;
                            break;
                        }

                    } else {
                        this.sessionPropertyTable.add(currRow, newDP);
                        dirInserted = true;
                        break;
                    }
                }
                currRow++;
            }

            if (!dirInserted){
                this.sessionPropertyTable.add(newDP);
            }
        }
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionPropertyConfigFile(Framework.TextData)
   */
    public void setSessionPropertyConfigFile(TextData fileName) {
        this.setSessionPropertyConfigFile(fileName.toString());
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setResponseTimeout(int)
   */
    public void setResponseTimeout(int timeOut) {
        throw new UnsupportedOperationException(
                "HTTPAccess.setResponseTimeOut() is not implemented");
    }
   
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setSessionTimeOut(Framework.IntervalData)
   */
    public void setSessionTimeOut(IntervalData timeOutInterval) {
        //this.sessionTimeout = TimeOutInterval.longValue() / 1000;
        // SW | Aug-2007 | MT#841 | roll it down to our SessionMgr obj
        if (this.webSessionMgr!=null) {
            this.webSessionMgr.setSessionTimeOut(timeOutInterval);
        }
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#shareSessions(HTTP.HTTPAccess)
   */
    public void shareSessions(HTTPAccess primaryWebService) {
        UnsupportedOperationException errorVar = new UnsupportedOperationException("HTTPAccess.shareSessions() is not implemented");
        ErrorMgr.addError(errorVar);
        throw errorVar;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#showException(Framework.GenericException, javax.servlet.http.HttpServletResponse)
   */
    public HttpServletResponse showException(GenericException ex, HttpServletResponse response)
    {
        try {
            PrintWriter out = response.getWriter();
            //  Get the error type.
            TextData errType = new TextData();
            TextData iconName = new TextData();
            switch (Framework.Constants.SP_ER_ERROR) {
            case Framework.Constants.SP_ER_USER:
                errType = new TextData( "User Error" );
                iconName = new TextData( "user.gif" );
                break;
            case Framework.Constants.SP_ER_FATAL:
                errType = new TextData( "Fort&eacute Fatal Error" );
                iconName = new TextData( "fatal.gif" );
                break;
            case Framework.Constants.SP_ER_ERROR:
                errType = new TextData( "Fort&eacute Error" );
                iconName = new TextData( "forte.gif" );
                break;

            default:
                errType = new TextData( "Warning" );
            iconName = new TextData( "warning.gif" );
            break;

            //  Generate an HTML page to show errors.
            }
            //TextData returnData = new TextData();
            out.println( "<HTML>" );
            out.println("<HEAD><TITLE>" + errType.toString());

            out.println("</TITLE></HEAD>");
            out.println("<CENTER><Img Src=\"/forte/icons/" + iconName + "\" Alt=\"" + errType.toString()
                    + "\"></CENTER>\r\n<BR><BR>\r\n");
            /*
            TextData exMsg = new TextData();
            exMsg.concat(ex.getMessage()).concat("\n").concat("<BR><I>Error detected at method: ");
            exMsg.concat(ex.getDetectingMethod());
            exMsg.concat("\n");
            exMsg.concat("<I>\n");
            int mOff = 0;
            int bit = 0;
            exMsg.setOffset(0);
            while (exMsg.moveToChar("\n")) {
                bit = bit+1;

                if (((boolean)(bit == 1))) {
                    returnData.concat("<H4>");
                    returnData.concat(exMsg.copyRange(mOff, exMsg.getOffset()));
                    returnData.concat("</H4>\r\n");
                }
                else {
                    returnData.concat(exMsg.copyRange(mOff, exMsg.getOffset()));
                    returnData.concat("<BR>\r\n");
                }
                exMsg.moveNext();
                mOff = exMsg.getOffset();

        }
             */
            if (ex instanceof HTMLScannerException) {
                HTMLScannerException hse = ((HTMLScannerException)ex);

                if (hse.getSourceLine() != null) {
                    out.println("<BR>Source line: <HR><TT>" + hse.getSourceLine() + "<BR>");

                    if ((boolean)(hse.getCharOffset() >= 1)) {
                        for (int i = 1; i <= hse.getCharOffset(); i++) {
                            out.print("&nbsp;");
                        }
                        //  caret
                        out.print("&#94;");
                    }
                    out.print("<BR></TT><HR>Line Number:&nbsp;");
                    out.print(hse.getLineNumber());
                    out.print("&nbsp; Character Offset:&nbsp;");
                    out.print(hse.getCharOffset());
                }

            }

            out.println("<HR></BODY></HTML>");
        } catch (IOException e) {
            HTTPAccess.getWebEntLogger().error("Unhandled exception", e);
        }

        return response;
    }


    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#validateSession(javax.servlet.http.HttpServletRequest)
   */
    public boolean validateSession(HttpServletRequest request) {
      // -------------------------------------------------------------------
      // TF:17/02/2009:DET-73:Do not create the session when we validate it.
      // -------------------------------------------------------------------
        if (request.getSession(false) == null) {
            HTTPAccess.getWebEntLogger().debug("HTTPAccess::ValidateSession : Returning FALSE since request.CurrentSession is null" );
            return false;
        }
      // ---------------------------------------------------------------------------------------------------------------
      // TF:17/02/2009:DET-73:There is no need to invoke timeout code, as the servlet contain will have done this for us
      // when we checked the session.
      // ---------------------------------------------------------------------------------------------------------------
      /*
        else {
            DateTimeData currTime = new DateTimeData();
            DateTimeData expireTime = new DateTimeData();

            currTime.setCurrent();

            expireTime.add(new DateTimeData(new Date(request.getSession().getLastAccessedTime())), new IntervalData(request.getSession().getMaxInactiveInterval()));

            if (currTime.isGreaterThan(expireTime).getValue()) {
              if (HTTPAccess.getWebEntLogger().isDebugEnabled()) {
                  HTTPAccess.getWebEntLogger().debug("HTTPAccess::ValidateSession : Returning FALSE since session " + request.getSession().toString() +
                          "has expired\nLastAccessedTime = " + request.getSession().getLastAccessedTime() +
                          ", SessionTimeOut = " + request.getSession().getMaxInactiveInterval() );
              }
                return false;
            }
            else {

              if (HTTPAccess.getWebEntLogger().isDebugEnabled()) {
                  HTTPAccess.getWebEntLogger().debug("HTTPAccess::ValidateSession : Returning TRUE since session " + request.getSession().toString() +
                          "has expired\nLastAccessedTime = " + request.getSession().getLastAccessedTime() +
                          ", SessionTimeOut = " + request.getSession().getMaxInactiveInterval() );
              }
                //request.getSession().setLastAccessedTime(currTime);
            }
        }
      */
        return true;
    }
   
    public void duplicateIntoTarget(HTTPAccess pTarget, boolean pDeep) {
        try {
            pTarget = ((HTTPAccess)this.clone());
        } catch (CloneNotSupportedException e) {
            Logger.getLogger("task.part.logmgr").error("Unhandled exception", e);
        }
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#getDefaultCookie()
   */
    public Cookie getDefaultCookie() {
        return defaultCookie;
    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#setDefaultCookie(javax.servlet.http.Cookie)
   */
    public void setDefaultCookie(Cookie defaultCookie) {
        this.defaultCookie = defaultCookie;
    }
    /**
     *
     */
    public void fireChange() {
        // Nobody should be dumb enough to map a Scanner object
    }

    public transient PropertyChangeSupport qq_Listeners = new PropertyChangeSupport(this);

    public synchronized void addPropertyChangeListener(String property, PropertyChangeListener listener) {
        if (qq_Listeners == null)
            qq_Listeners = new PropertyChangeSupport(this);
        qq_Listeners.addPropertyChangeListener(property, listener);
    }
    public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
        if (qq_Listeners == null)
            qq_Listeners = new PropertyChangeSupport(this);
        qq_Listeners.removePropertyChangeListener(listener);
    }
    public synchronized PropertyChangeSupport getPropertyListeners() {
        if (qq_Listeners == null)
            qq_Listeners = new PropertyChangeSupport(this);
        return this.qq_Listeners;
    }
    public synchronized void propertyChange(PropertyChangeEvent pcEvt) {

    }
    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#isSessionMgmtEnabled()
   */
    public boolean isSessionMgmtEnabled() {
        return sessionMgmtEnabled;
    }

    /* (non-Javadoc)
   * @see HTTP.IHTTPAccess#fetchSessionProperty(javax.servlet.http.HttpServletRequest)
   */
    public int fetchSessionProperty(HttpServletRequest request){
        String pathName;
        if (isPageRequest(request)){
            pathName = HTMLScanner.getParameter(request, "PageName", true);
        } else if (isTemplateRequest(request)){
            pathName = HTMLScanner.getParameter(request, "TemplateName", true);
        } else {
            SessionException errorVar = new SessionException("Request does not contain PageName or TemplateName");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        int requestedSessionProperty = SESSION_UNSPECIFIED;

        String newPathName;
        String beginChar = pathName.substring(0, 1);
        if (!beginChar.equals("/")){
            newPathName = "/" + pathName;
        } else {
            newPathName = pathName;
        }
        String endChar = pathName.substring(pathName.length()-1);
        if (!endChar.equals("/")){
            newPathName += "/";
        }
        Iterator<PathSessionProperty> it = this.sessionPropertyTable.iterator();
        while (it.hasNext()){
            PathSessionProperty aSessionProp = it.next();
            TextData td = new TextData(newPathName);
            if (td.moveToString(aSessionProp.getPathName(), false, true) == true){
                if (td.getOffset() == 0){
                    requestedSessionProperty = aSessionProp.getSessionProperty();
                    break;
                }
            }
        }
        return requestedSessionProperty;
    }
    protected boolean isTemplateRequest(HttpServletRequest request) {
        return (HTMLScanner.getParameter(request, "TemplateName", true) != null);
    }

    protected boolean isPageRequest(HttpServletRequest request) {
        return (HTMLScanner.getParameter(request, "PageName", true) != null);
    }

// end class HTTPAccess
TOP

Related Classes of HTTP.HTTPAccess

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.