Package HTTPSupport

Source Code of HTTPSupport.HTTPBaseMessage

/*
Copyright (c) 2003-2008 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 HTTPSupport;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.Iterator;

import javax.servlet.http.Cookie;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import Framework.Application;
import Framework.DateTimeData;
import Framework.DistributedAccessException;
import Framework.FrameworkUtils;
import Framework.LogMgr;
import Framework.StringUtils;
import Framework.TextData;

/**
* The HTTPBaseMesssage class  is the base class for the {@link HTTPBaseRequest} and {@link HTTPBaseResponse} classes.
*/
@SuppressWarnings("serial")
public class HTTPBaseMessage extends HeaderHolder implements Serializable, GenericMessage {

    // ---------
    // Constants
    // ---------
    public static final String BASE64CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    public static final String HTTP_SCHEME = "HTTP";      // @NoChangeOnCopy -- Marker to jcTOOL not to apply package translation to this line

    // ----------
    // Attributes
    // ----------
    protected String ContentType = "text/html";
    protected HTTPHelper httpHelper;
    protected int majorVersion;
    protected int minorVersion;
    protected GenericEntity body = new Entity();;
    protected GenericSession session;
    protected Array_Of_Cookie<Cookie> cookies;
    protected String method;

    // ------------
    // Constructors
    // ------------
    public HTTPBaseMessage() {
        // Explicitly call the superclass constructor to prevent the implicit
        // call
        super();

        this.majorVersion = Constants.HTTP_DEFAULT_MAJOR_VERSION;
        this.minorVersion = Constants.HTTP_DEFAULT_MINOR_VERSION;

        this.cookies = new Array_Of_Cookie<Cookie>();

        this.httpHelper = new HTTPHelper();

    }

    // ----------------------
    // Accessors and Mutators
    // ----------------------
    public void sethttpHelper(HTTPHelper pValue) {
        this.httpHelper = pValue;
    }

    public HTTPHelper gethttpHelper() {
        return this.httpHelper;
    }

    public void setmajorVersion(int pValue) {
        this.majorVersion = pValue;
    }

    public int getmajorVersion() {
        return this.majorVersion;
    }

    public void setminorVersion(int pValue) {
        this.minorVersion = pValue;
    }

    public int getminorVersion() {
        return this.minorVersion;
    }

    public void setbody(GenericEntity pValue) {
        this.body = pValue;
    }

    public GenericEntity getbody() {
        return this.body;
    }

    public GenericSession getsession() {
        return this.session;
    }

    public void setCookies(Array_Of_Cookie<Cookie> pValue) {
        this.cookies = pValue;
    }

    public Array_Of_Cookie<Cookie> getCookies() {
        return this.cookies;
    }

    // -------
    // Methods
    // -------
    /**
     * addCookie
     * <p>
     * <p>
     *
     * @param cookie
     *            Type: Cookie
     */
    public void addCookie(Cookie cookie) {
        this.cookies.add(cookie);
    }

    /**
     * advertise
     * <p>
     * <p>
     *
     * @param obj
     *            Type: Object
     * @param param
     *            Type: String
     */
    public void advertise(Object obj, String param) {
        this.httpHelper.advertise(obj, param);
    }

    /**
     * decodeBase64
     * <p>
     * <p>
     *
     * @param encodedText
     *            Type: TextData
     * @return TextData
     */
    public TextData decodeBase64(TextData encodedText) {
        // TF:7/7/07 - Recoded this method to use the apache libraries, removing the non-compiling method
        String result = new String(Base64.decodeBase64(encodedText.asByteArray()));
        return new TextData(result);
    }

    /**
     * encodeBase64
     * <p>
     * <p>
     *
     * @param plainText
     *            Type: TextData
     * @return TextData
     */
    public TextData encodeBase64(TextData plainText) {
        // TF:7/7/07 - Recoded this method to use the apache libraries, removing the non-compiling method
        String base64Text = new String(Base64.encodeBase64(plainText.asByteArray()));
        return new TextData(base64Text);
    }

    /**
     * fromHeaderLine
     * <p>
     * This method must be overloaded by HTTPBaseRequest and HTTPBaseResponse
     * <br>
     * <p>
     *
     * @param line
     *            Type: String
     */
    public void fromHeaderLine(String line) {
    }

    /**
     * getContentLength
     * <p>
     * <p>
     *
     * @return int
     */
    public int getContentLength() {
        return this.body.getIntHeader(Constants.HTTP_HEADER_CONTENT_LENGTH);
    }

    /**
     * getContentType
     * <p>
     * <p>
     *
     * @return String
     */
    public String getContentType() {

        if (this.body != null) {
            return this.body.getHeader(Constants.HTTP_HEADER_CONTENT_TYPE);
        }
        return null;
    }

    // Method getCookies() : Framework.Array of
    // HTTPSupport.Cookie skipped because it is replaced by
    // accessor / mutator.
    /**
     * getDateHeader
     * <p>
     * <p>
     *
     * @return DateTimeData
     */
    public DateTimeData getDateHeader() {
        String date = null;
        date = this.getHeader(Constants.HTTP_HEADER_DATE);

        if (date != null) {
            return this.httpHelper.fromStringDate(date);
        }

        return null;
    }

    // Method getMajorVersion() : integer skipped because it is replaced by
    // accessor / mutator.
    // Method getMinorVersion() : integer skipped because it is replaced by
    // accessor / mutator.
    // Method getSession() : GenericSession skipped because it is replaced by
    // accessor / mutator.
    /**
     * getStringVersion
     * <p>
     * <p>
     *
     * @return String
     */
    public String getStringVersion() {
        TextData txt = new TextData(HTTPBaseMessage.HTTP_SCHEME);
        txt.concat("/");
        txt.concat(this.majorVersion);
        txt.concat(".");
        txt.concat(this.minorVersion);
        return txt.toString();
    }

    /**
     * prepareToSend
     * <p>
     * Fill the header with the default value. This method is called <br>
     * before the message is sent. <br>
     * <p>
     */
    public void prepareToSend() {

        if (LogMgr.getInstance().test(
                Framework.Constants.SP_MT_DEBUG,
                HTTPSupport.Constants.HTTP_SVC,
                HTTPSupport.Constants.HTTP_TRACE, 10)) {
            Logger.getLogger("task.part.logmgr").info(
                    "HTTPBaseMessage.prepareToSend");
        }

        //
        //  Check the cookie list consistency
        //
        CookieManager.validate(this);

        // if self.body <> NIL
        //   then
        //     length : integer;
        //
        //     self.setHeader(HTTP_HEADER_CONTENT_TYPE,
        //               self.body.getHeader(HTTP_HEADER_CONTENT_TYPE));
        //
        //     if self.body.Items() = 0
        //     then
        //       //length = self.entitySize(self.body);
        //       //else
        //       // Single entity
        //       //length = self.body.size();
        //     end if;
        //
        //     self.setIntHeader(HTTP_HEADER_CONTENT_LENGTH, length);
        //   else
        //     self.setIntHeader(HTTP_HEADER_CONTENT_LENGTH, 0);
        //   end if;
    }

    /**
     * presetDefaultHeaders
     * <p>
     * Set the default values of the Generic HTTP headers. <br>
     * <p>
     */
    public void presetDefaultHeaders() {
        this.setHeader(
                Constants.HTTP_HEADER_CACHE_CONTROL,
                Constants.HTTP_HEADER_NO_CACHE_VALUE);

        //  Connection
        //  ??? Connection management
        //  Pragma - include no-cache, for HTTP 1.0 server
        this.setHeader(
                Constants.HTTP_HEADER_PRAGMA,
                Constants.HTTP_HEADER_NO_CACHE_VALUE);

        //  Date
        //  Trailer
        //  Transfer-Encoding
        //  Upgrade
        //  Via
        //  Warning
    }

    /**
     * processReceived
     * <p>
     * This method is called when a message has been received (request <br>
     * or response) after the header and body have been deserialized. <br>
     * The purpose of this method is to be overloaded by a specialized <br>
     * HTTP user message class, allowing the user class to do some <br>
     * work behind the scene before its specialized object becomes <br>
     * fully visible and usable. <br>
     * <p>
     */
    public void processReceived() {
    }

    /**
     * removeCookie
     * <p>
     * <p>
     *
     * @param name
     *            Type: String
     */
    public void removeCookie(String name) {
        if (this.cookies != null) {
            for (Iterator<Cookie> qq_it = this.cookies.iterator(); qq_it.hasNext();) {
                Cookie cookie = (Cookie) qq_it.next();

                if (StringUtils.equals(cookie.getName(), name)) {

                    if (LogMgr
                            .getInstance()
                            .test(
                                    Framework.Constants.SP_MT_DEBUG,
                                    HTTPSupport.Constants.HTTP_SVC,
                                    HTTPSupport.Constants.HTTP_TRACE,
                                    20)) {
                        Logger
                                .getLogger("task.part.logmgr")
                                .info("HTTPBaseMessage.removeCookie - removed:");
                        Logger.getLogger("task.part.logmgr")
                                .error(cookie);
                    }

                    this.cookies.remove(cookie);
                    break;
                }
            }
        }
    }

    /**
     * removeCookie
     * <p>
     * <p>
     *
     * @param cookie
     *            Type: Cookie
     */
    public void removeCookie(Cookie cookie) {

        if (cookie != null) {
            this.removeCookie(cookie.getName());
        }
    }

    // Method setBody(body : GenericEntity) skipped because it is replaced by
    // accessor / mutator.
    /**
     * setContentType
     * <p>
     * <p>
     *
     * @param type
     *            Type: String
     */
    public void setContentType(String type) {

        if (this.body != null) {
            this.body
                    .setHeader(
                            HTTPSupport.Constants.HTTP_HEADER_CONTENT_TYPE,
                            type);
        }
    }

    /**
     * setDateHeader
     * <p>
     * <p>
     *
     * @param date
     *            Type: DateTimeData (default in Forte: NIL)
     */
    public void setDateHeader(DateTimeData date) {

        if (date == null) {
            DateTimeData current = new DateTimeData();
            current.setCurrent();
            this.setHeader(
                    Constants.HTTP_HEADER_DATE,
                    this.httpHelper.toStringDate(current));
        } else {
            this.setHeader(
                    Constants.HTTP_HEADER_DATE,
                    this.httpHelper.toStringDate(date));
        }
    }

    /**
     * setSession
     * <p>
     * <p>
     *
     * @param session
     *            Type: GenericSession
     */
    public void setSession(GenericSession session) {

        if (((Object) session) instanceof HTTPSession) {
            this.session = (HTTPSession) session;
            session.setbaseMessage(this);
        } else {
            DistributedAccessException ex = new DistributedAccessException();
            TextData className = new TextData();

            if (session != null) {
                className.setValue(FrameworkUtils.getClassName(((Object) session).getClass()));
            }
            String message = Application.getMsgCatalog().getString(
                  Constants.HTTP_SET,
                  Constants.HTTP_MSG_NOT_HTTP_SESSION);
            ex.setWithParams( Framework.Constants.SP_ER_USER, message, className);
            throw ex;
        }
    }

    /**
     * setVersion
     * <p>
     * Version supported are 1.0 and 1.1 <br>-> Update http.msg exception
     * message if a new version is added <br>
     * <p>
     *
     * @param major
     *            Type: int
     * @param minor
     *            Type: int
     */
    public void setVersion(int major, int minor) {

        if (this.majorVersion == 1
                && (this.minorVersion == 1 || this.minorVersion == 0)) {
            this.minorVersion = minor;
            this.majorVersion = major;
        } else {
            DistributedAccessException ex = new DistributedAccessException();
            TextData txtVersion = new TextData(this.majorVersion,
                    TextData.qq_Resolver.cINTEGERVALUE);

            txtVersion.concat(".");
            txtVersion.concat(this.minorVersion);

            String message = Application.getMsgCatalog().getString(
              Constants.HTTP_SET,
              Constants.HTTP_MSG_VERSION_NOT_SUPPORTED);
            ex.setWithParams( Framework.Constants.SP_ER_USER, message, txtVersion);
            throw ex;
        }
    }

    /**
     * toHeaderLine
     * <p>
     * This method must be overloaded by HTTPBaseRequest and HTTPBaseResponse
     * <br>
     * <p>
     *
     * @return String
     */
    public String toHeaderLine() {
        return null;
    }

    public GenericEntity getBody() {
        return this.body;
    }

    public int getMajorVersion() {
        return this.majorVersion;
    }

    public int getMinorVersion() {
        return this.minorVersion;
    }

    public GenericSession getSession() {
        return this.session;
    }

    public void setBody(GenericEntity body) {
        this.body = body;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    /**
     * @return Returns the method.
     */
    public String getMethod() {
        return method;
    }

    protected HttpURLConnection conn;
} // end class HTTPBaseMessage
// c Pass 2 Conversion Time: 953 milliseconds
TOP

Related Classes of HTTPSupport.HTTPBaseMessage

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.