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

📄 cmsrequesthttpservlet.java

📁 java 编写的程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
* File   : $Source: /usr/local/cvs/opencms/src/com/opencms/core/CmsRequestHttpServlet.java,v $
* Date   : $Date: 2002/02/06 15:01:54 $
* Version: $Revision: 1.27 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2001  The OpenCms Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* For further information about OpenCms, please see the
* OpenCms Website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package com.opencms.core;

import com.opencms.util.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Implementation of the CmsRequest interface.
 *
 * This implementation uses a HttpServletRequest as original request to create a
 * CmsRequestHttpServlet. This either can be a normal HttpServletRequest or a
 * CmsMultipartRequest which is used to upload file into the OpenCms. <br>
 *
 * This class contains a modification of the MultipartRequest published in the O'Reilly
 * book <it>Java Servlet Programming </it> by J. Junte, <a href=http://www.servlets.com/ > www.servlets.com </a>
 * <p>
 * It Constructs a new MultipartRequest to handle the specified request,
 * saving any uploaded files to the given directory, and limiting the upload size to
 * a maxumum size of 8 MB.
 * <p>
 * The idea is to modify the given MultiPartRequest to make it transparent to normal
 * requests and store file into CmsFile objects so that they can be transferred into
 * the OpenCms document database.
 *
 * @author Michael Emmerich
 * @author Alexander Lucas
 * @version $Revision: 1.27 $ $Date: 2002/02/06 15:01:54 $
 */
public class CmsRequestHttpServlet implements I_CmsConstants,I_CmsLogChannels,I_CmsRequest {

    /**
     * Define the maximum size for an uploaded file (8 MB)
     */
    private static final int DEFAULT_MAX_POST_SIZE = 8192 * 1024; // 8 Meg

    /**
     * Definition of the error message for an empty request.
     */
    static final String C_REQUEST_NOTNULL = "The Request cannot be null.";

    /**
     * Definition of the error message for being not a multipart request.
     */
    static final String C_REQUEST_NOMULTIPART = "Posted content type isn't multipart/form-data";

    /**
     * Definition of the error message for a negative maximum post size.
     */
    static final String C_REQUEST_SIZENOTNEGATIVE = "The maxPostSize must be positive.";

    /**
     * Definition of the error message for a premature end.
     */
    static final String C_REQUEST_PROMATUREEND = "Corrupt form data: premature ending";

    /**
     * Definition of the error message for missing boundary.
     */
    static final String C_REQUEST_NOBOUNDARY = "Separation boundary was not specified";

    /**
     * The maximum size of the uploaded data.
     */
    private int m_maxSize = DEFAULT_MAX_POST_SIZE;

    /**
     * The original request.
     */
    private HttpServletRequest m_req;

    /**
     * The path to the resource
     */
    private String m_path = null;

    /**
     * The type of theis CmsRequest.
     */
    private int m_type = C_REQUEST_HTTP;

    /**
     * Storage for all uploaded files.
     */
    private Hashtable m_files = new Hashtable();

    /**
     * Storage for all uploaded name values
     */
    private Hashtable m_parameters = new Hashtable();
    int filecounter = 0;

    /**
     * The data from the original request. We save them to get them after the
     * original request is expired.
     */
    private String m_webAppUrl="";
    private String m_servletUrl="";
    private String m_serverName="";
    private String m_scheme="";
    private int m_serverPort;

    /**
     * Constructor, creates a new CmsRequestHttpServlet object.
     *
     * @param req The original HttpServletRequest used to create this CmsRequest.
     */
    CmsRequestHttpServlet(HttpServletRequest req) throws IOException {
        m_req = req;

        // get the webAppUrl and the servletUrl
        try {
            m_webAppUrl = m_req.getContextPath();
        } catch(NoSuchMethodError err) {
            // this is the old servlet-api without this method
            // ignore this missing method and the context-path
        }
        m_serverName = m_req.getServerName();
        m_scheme = m_req.getScheme();
        m_serverPort = m_req.getServerPort();
        m_servletUrl = m_webAppUrl + m_req.getServletPath();
        // Test if this is a multipart-request.
        // If it is, extract all files from it.
        String type = req.getHeader("content-type");
        if((type != null) && type.startsWith("multipart/form-data")&& (req.getContentLength() > -1)) {
            readRequest();
        }
        if(m_req.getPathInfo().indexOf("?") != -1) {
            if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && m_req.getQueryString() != null && m_req.getQueryString().indexOf("/") != -1) {
                A_OpenCms.log(C_OPENCMS_CRITICAL, "WARNING: URL parameters were not extracted properly.");
                A_OpenCms.log(C_OPENCMS_CRITICAL, "This may be caused by a bug in your servlet environment with handling \"/\" characters. ");
                A_OpenCms.log(C_OPENCMS_CRITICAL, "Please make sure you are escaping all special chars (including \"/\") in your HTML forms.");
                A_OpenCms.log(C_OPENCMS_CRITICAL, m_req.getPathInfo());
            }
            throw new IOException("URL parameters not extracted properly by servlet environment. " + m_req.getPathInfo());
        }
    }

    /**
     * Extracts and returns the boundary token from a line.
     *
     * @param Line with boundary from input stream.
     * @return The boundary token.
     */
    private String extractBoundary(String line) {
        int index = line.indexOf("boundary=");
        if(index == -1) {
            return null;
        }

        // 9 for "boundary="
        String boundary = line.substring(index + 9);

        // The real boundary is always preceeded by an extra "--"
        boundary = "--" + boundary;
        return boundary;
    }

    /**
     * Extracts and returns the content type from a line, or null if the
     * line was empty.
     * @param line Line from input stream.
     * @return Content type of the line.
     * @exception IOException Throws an IOException if the line is malformatted.
     */
    private String extractContentType(String line) throws IOException {
        String contentType = null;

        // Convert the line to a lowercase string
        String origline = line;
        line = origline.toLowerCase();

        // Get the content type, if any
        if(line.startsWith("content-type")) {
            int start = line.indexOf(" ");
            if(start == -1) {
                throw new IOException("Content type corrupt: " + origline);
            }
            contentType = line.substring(start + 1);
        }
        else {
            if(line.length() != 0) {

                // no content type, so should be empty
                throw new IOException("Malformed line after disposition: " + origline);
            }
        }
        return contentType;
    }

    /**
     * Extracts and returns disposition info from a line, as a String array
     * with elements: disposition, name, filename.  Throws an IOException
     * if the line is malformatted.
     *
     * @param line Line from input stream.
     * @return Array of string containing disposition information.
     * @exception IOException Throws an IOException if the line is malformatted.
     */
    private String[] extractDispositionInfo(String line) throws IOException {

        // Return the line's data as an array: disposition, name, filename
        String[] retval = new String[3];

        // Convert the line to a lowercase string without the ending \r\n
        // Keep the original line for error messages and for variable names.
        String origline = line;
        line = origline.toLowerCase();

        // Get the content disposition, should be "form-data"
        int start = line.indexOf("content-disposition: ");
        int end = line.indexOf(";");
        if(start == -1 || end == -1) {
            throw new IOException("Content disposition corrupt: " + origline);
        }
        String disposition = line.substring(start + 21, end);
        if(!disposition.equals("form-data")) {
            throw new IOException("Invalid content disposition: " + disposition);
        }

        // Get the field name
        // start at last semicolon
        start = line.indexOf("name=\"", end);

        // skip name=\"
        end = line.indexOf("\"", start + 7);
        if(start == -1 || end == -1) {
            throw new IOException("Content disposition corrupt: " + origline);
        }
        String name = origline.substring(start + 6, end);

        // Get the filename, if given
        String filename = null;

        // start after name
        start = line.indexOf("filename=\"", end + 2);

        // skip filename=\"
        end = line.indexOf("\"", start + 10);

        // note the !=
        if(start != -1 && end != -1) {
            filename = origline.substring(start + 10, end);

            // The filename may contain a full path.  Cut to just the filename.
            int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
            if(slash > -1) {
                filename = filename.substring(slash + 1); // past last slash
            }
            if(filename.equals("")) {
                filename = "unknown"; // sanity check
            }
        }

        // Return a String array: disposition, name, filename
        retval[0] = disposition;
        retval[1] = name;
        retval[2] = filename;
        return retval;
    }

    /**
     * Returns the content of an uploaded file.
     * Returns null if no file with this name has been uploaded with this request.
     * Returns an empty byte[] if a file without content has been uploaded.
     *
     * @param name The name of the uploaded file.
     * @return The selected uploaded file content.
     */
    public byte[] getFile(String name) {
        byte[] content = null;
        content = (byte[])m_files.get(name);
        return content;
    }

    /**
     * Returns the names of all uploaded files in this request.
     * Returns an empty eumeration if no files were included in the request.
     *
     * @return An Enumeration of file names.
     */
    public Enumeration getFileNames() {
        Enumeration names = m_files.keys();
        return names;
    }

    /**
     * Returns the original request that was used to create the CmsRequest.
     *
     * @return The original request of the CmsRequest.
     */
    public Object getOriginalRequest() {
        return m_req;
    }

    /**
     * Returns the type of the request that was used to create the CmsRequest.
     * The returned int must be one of the constants defined above in this interface.
     *
     * @return The type of the CmsRequest.
     */
    public int getOriginalRequestType() {
        return m_type;
    }

    /**
     * Returns the value of a named parameter as a String.
     * Returns null if the parameter does not exist or an empty string if the parameter
     * exists but without a value.
     *
     * @param name The name of the parameter.
     * @returns The value of the parameter.
     */
    public String getParameter(String name) {
        String parameter = null;

        // Test if this is a multipart-request.
        // If it is, extract all files from it.
        String type = m_req.getHeader("content-type");
        if((type != null) && type.startsWith("multipart/form-data")) {
            parameter = (String)m_parameters.get(name);
        }
        else {
            parameter = m_req.getParameter(name);
        }

        /*   if(parameter != null && !"".equals(parameter) && (parameter.indexOf("%") != -1)) {
        if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
            A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsRequestHttpServlet] encoding required for parameter " + name + "=" + parameter);
        }
        parameter = Encoder.unescape(parameter);
        }*/
        return parameter;
    }

    /**
     * Returns all parameter names as an Enumeration of String objects.
     * Returns an empty Enumeratrion if no parameters were included in the request.
     *

⌨️ 快捷键说明

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