⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 servletunithttpresponse.java

📁 displaytag-1.0修正版
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * patched ServletUnitHttpResponse.java, needed to run Spring tests. Needed till next httpunit release.
 * see http://sourceforge.net/tracker/index.php?func=detail&aid=1044820&group_id=6550&atid=106550
 */

package com.meterware.servletunit;

/***********************************************************************************************************************
 * $Id: ServletUnitHttpResponse.java,v 1.1 2004/10/11 20:22:56 fgiust Exp $ Copyright (c) 2000-2003, Russell Gold
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
 * notice and this permission notice shall be included in all copies or substantial portions of the Software. THE
 * SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 **********************************************************************************************************************/
import com.meterware.httpunit.HttpUnitUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;
import java.util.ArrayList;
import java.util.TimeZone;
import java.util.Date;
import java.text.SimpleDateFormat;

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


class ServletUnitHttpResponse implements HttpServletResponse
{

    // rfc1123-date is "Sun, 06 Nov 1994 08:49:37 GMT"
    private static final String RFC1123_DATE_SPEC = "EEE, dd MMM yyyy hh:mm:ss z";

    private boolean _committed;

    private Locale _locale;

    /**
     * @deprecated Use encodeURL(String url)
     */
    public String encodeUrl(String url)
    {
        return encodeURL(url);
    }

    /**
     * Adds the specified cookie to the response. It can be called multiple times to set more than one cookie.
     */
    public void addCookie(Cookie cookie)
    {
        _cookies.addElement(cookie);
    }

    /**
     * Checks whether the response message header has a field with the specified name.
     */
    public boolean containsHeader(String name)
    {
        return _headers.containsKey(name.toUpperCase());
    }

    /**
     * @deprecated Use encodeRedirectURL(String url)
     */
    public String encodeRedirectUrl(String url)
    {
        return encodeRedirectURL(url);
    }

    /**
     * Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL
     * unchanged. The implementation of this method should include the logic to determine whether the session ID needs
     * to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL
     * encoding is unnecessary.
     */
    public String encodeURL(String url)
    {
        return url;
    }

    /**
     * Encodes the specified URL for use in the <code>sendRedirect</code> method or, if encoding is not needed,
     * returns the URL unchanged. The implementation of this method should include the logic to determine whether the
     * session ID needs to be encoded in the URL. Because the rules for making this determination differ from those used
     * to decide whether to encode a normal link, this method is seperate from the <code>encodeUrl</code> method.
     */
    public String encodeRedirectURL(String url)
    {
        return url;
    }

    /**
     * Sends a temporary redirect response to the client using the specified redirect location URL. The URL must be
     * absolute (for example, <code><em>https://hostname/path/file.html</em></code>). Relative URLs are not
     * permitted here.
     */
    public void sendRedirect(String location) throws IOException
    {
        setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        setHeader("Location", location);
    }

    /**
     * Sends an error response to the client using the specified status code and descriptive message. If setStatus has
     * previously been called, it is reset to the error status code. The message is sent as the body of an HTML page,
     * which is returned to the user to describe the problem. The page is sent with a default HTML header; the message
     * is enclosed in simple body tags (&lt;body&gt;&lt;/body&gt;).
     */
    public void sendError(int sc) throws IOException
    {
        sendError(sc, "");
    }

    /**
     * Sends an error response to the client using the specified status code and descriptive message. If setStatus has
     * previously been called, it is reset to the error status code. The message is sent as the body of an HTML page,
     * which is returned to the user to describe the problem. The page is sent with a default HTML header; the message
     * is enclosed in simple body tags (&lt;body&gt;&lt;/body&gt;).
     */
    public void sendError(int sc, String msg) throws IOException
    {
        setStatus(sc);
        _statusMessage = msg;

        _writer = null;
        _servletStream = null;

        setContentType("text/html");
        getWriter().println("<html><head><title>" + msg + "</title></head><body>" + msg + "</body></html>");
    }

    /**
     * Sets the status code for this response. This method is used to set the return status code when there is no error
     * (for example, for the status codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, the
     * <code>sendError</code> method should be used instead.
     */
    public void setStatus(int sc)
    {
        _status = sc;
    }

    /**
     * @deprecated As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use
     * setStatus(int), to send an error with a description use sendError(int, String). Sets the status code and message
     * for this response.
     */
    public void setStatus(int sc, String msg)
    {
        setStatus(sc);
    }

    /**
     * Adds a field to the response header with the given name and value. If the field had already been set, the new
     * value overwrites the previous one. The <code>containsHeader</code> method can be used to test for the presence
     * of a header before setting its value.
     */
    public void setHeader(String name, String value)
    {
        ArrayList values = new ArrayList();
        values.add(value);
        synchronized (_headers)
        {
            _headers.put(name.toUpperCase(), values);
        }
    }

    /**
     * Adds a field to the response header with the given name and integer value. If the field had already been set, the
     * new value overwrites the previous one. The <code>containsHeader</code> method can be used to test for the
     * presence of a header before setting its value.
     */
    public void setIntHeader(String name, int value)
    {
        setHeader(name, asHeaderValue(value));
    }

    private String asHeaderValue(int value)
    {
        return Integer.toString(value);
    }

    /**
     * Adds a field to the response header with the given name and date-valued field. The date is specified in terms of
     * milliseconds since the epoch. If the date field had already been set, the new value overwrites the previous one.
     * The <code>containsHeader</code> method can be used to test for the presence of a header before setting its
     * value.
     */
    public void setDateHeader(String name, long date)
    {
        setHeader(name, asDateHeaderValue(date));
    }

    private String asDateHeaderValue(long date)
    {
        Date value = new Date(date);
        SimpleDateFormat formatter = new SimpleDateFormat(RFC1123_DATE_SPEC, Locale.US);
        formatter.setTimeZone(TimeZone.getTimeZone("Greenwich Mean Time"));
        return formatter.format(value);
    }

    /**
     * Returns the name of the character set encoding used for the MIME body sent by this response.
     */
    public String getCharacterEncoding()
    {
        return _encoding;
    }

    /**
     * Sets the content type of the response the server sends to the client. The content type may include the type of
     * character encoding used, for example, <code>text/html; charset=ISO-8859-4</code>.
     * <p>
     * You can only use this method once, and you should call it before you obtain a <code>PrintWriter</code> or
     * {@link ServletOutputStream}object to return a response.
     */
    public void setContentType(String type)
    {
        String[] typeAndEncoding = HttpUnitUtils.parseContentTypeHeader(type);

        _contentType = typeAndEncoding[0];
        if (typeAndEncoding[1] != null)
            _encoding = typeAndEncoding[1];

        if (_encoding.equalsIgnoreCase(HttpUnitUtils.DEFAULT_CHARACTER_SET))
        {
            setHeader("Content-Type", type);
        }
        else
        {
            setHeader("Content-Type", _contentType + "; charset=" + _encoding);
        }
    }

    /**
     * Returns a {@link ServletOutputStream}suitable for writing binary data in the response. The servlet engine does
     * not encode the binary data.
     * @exception IllegalStateException if you have already called the <code>getWriter</code> method
     */
    public ServletOutputStream getOutputStream() throws IOException
    {
        if (_writer != null)
            throw new IllegalStateException("Tried to create output stream; writer already exists");
        if (_servletStream == null)
        {
            _outputStream = new ByteArrayOutputStream();
            _servletStream = new ServletUnitOutputStream(_outputStream);
        }
        return _servletStream;
    }

    /**
     * Returns a <code>PrintWriter</code> object that you can use to send character text to the client. The character
     * encoding used is the one specified in the <code>charset=</code> property of the {@link #setContentType}method,
     * which you must call <i>before </i> you call this method.
     * <p>
     * If necessary, the MIME type of the response is modified to reflect the character encoding used.
     * <p>
     * You cannot use this method if you have already called {@link #getOutputStream}for this
     * <code>ServletResponse</code> object.
     * @exception UnsupportedEncodingException if the character encoding specified in <code>setContentType</code>
     * cannot be used
     * @exception IllegalStateException if the <code>getOutputStream</code> method has already been called for this
     * response object; in that case, you can't use this method
     */
    public PrintWriter getWriter() throws UnsupportedEncodingException
    {
        if (_servletStream != null)
            throw new IllegalStateException("Tried to create writer; output stream already exists");
        if (_writer == null)
        {
            _outputStream = new ByteArrayOutputStream();
            _writer = new PrintWriter(new OutputStreamWriter(_outputStream, getCharacterEncoding()));
        }
        return _writer;
    }

    /**
     * Sets the length of the content the server returns to the client. In HTTP servlets, this method sets the HTTP
     * Content-Length header.
     */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -