opencmshttpservlet.java

来自「java 编写的程序」· Java 代码 · 共 721 行 · 第 1/3 页

JAVA
721
字号
     * @exception IOException Thrown if user autherization fails.
     */
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {

        //Check for content type "form/multipart" and decode it
        String type = req.getHeader("content-type");
        CmsObject cms = null;
        if((type != null) && type.startsWith("multipart/form-data")) {


        //  req = new CmsMultipartRequest(req);
        }
        CmsRequestHttpServlet cmsReq = new CmsRequestHttpServlet(req);
        CmsResponseHttpServlet cmsRes = new CmsResponseHttpServlet(req, res, m_clusterurl);
        try {
            cms = initUser(cmsReq, cmsRes);
            if( !checkRelocation(cms) ) {
                // no redirect was done - deliver the ressource normally
                CmsFile file = m_opencms.initResource(cms);
                if(file != null) {

                    // If the CmsFile object is null, the resource could not be found.
                    // Stop processing in this case to avoid NullPointerExceptions
                    m_opencms.setResponse(cms, file);
                    m_opencms.showResource(cms, file);
                    updateUser(cms, cmsReq, cmsRes);
                }
            }
        }
        catch(CmsException e) {
            errorHandling(cms, cmsReq, cmsRes, e);
        }
    }

    /**
     * This method performs the error handling for the OpenCms.
     * All CmsExetions throns in the OpenCms are forwared to this method and are
     * processed here.
     *
     * @param cms The CmsObject
     * @param cmsReq   The clints request.
     * @param cmsRes   The servlets response.
     * @param e The CmsException to be processed.
     */
    private void errorHandling(CmsObject cms, I_CmsRequest cmsReq, I_CmsResponse cmsRes, CmsException e) {
        int errorType = e.getType();
        HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
        HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
        boolean canWrite = ((!cmsRes.isRedirected()) && (!cmsRes.isOutputWritten()));
        try {
            switch(errorType) {

              // access denied error - display login dialog
              case CmsException.C_ACCESS_DENIED:
                  if(canWrite) {
                    if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
                        A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Access denied. "+e.getStackTraceAsString());
                    }
                    requestAuthorization(req, res);
                  }

                  break;

              // file not found - display 404 error.
              case CmsException.C_NOT_FOUND:
                  if(canWrite) {
                    res.setContentType("text/HTML");

                    //res.getWriter().print(createErrorBox(e));
                    res.sendError(res.SC_NOT_FOUND);
                  }
                  break;

              case CmsException.C_SERVICE_UNAVAILABLE:
                  if(canWrite) {
                    res.sendError(res.SC_SERVICE_UNAVAILABLE, e.toString());
                  }
                  break;

              // https page and http request - display 404 error.
              case CmsException.C_HTTPS_PAGE_ERROR:
                  if(canWrite) {
                    if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
                        A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Trying to get a http page with a https request. "+e.getMessage());
                    }
                    res.setContentType("text/HTML");
                    res.sendError(res.SC_NOT_FOUND);
                  }
                  break;

              // https request and http page - display 404 error.
              case CmsException.C_HTTPS_REQUEST_ERROR:
                    if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
                        A_OpenCms.log(C_OPENCMS_INFO, "[OpenCmsServlet] Trying to get a https page with a http request. "+e.getMessage());
                    }
                  if(canWrite) {
                    res.setContentType("text/HTML");
                    res.sendError(res.SC_NOT_FOUND);
                  }
                  break;

              default:
                  if(canWrite) {
                    // send errorbox, but only if the request was not redirected
                    res.setContentType("text/HTML");

                    // set some HTTP headers preventing proxy servers from caching the error box
                    res.setHeader("Cache-Control", "no-cache");
                    res.setHeader("Pragma", "no-cache");
                    res.getWriter().print(createErrorBox(e, cms));
                  }
            //res.sendError(res.SC_INTERNAL_SERVER_ERROR);
            }
        }
        catch(IOException ex) {

        }
    }

    /**
     * Initialization of the OpenCms servlet.
     * Used instead of a constructor (Overloaded Servlet API method)
     * <p>
     * The connection information for the property database is read from the configuration
     * file and all resource brokers are initialized via the initalizer.
     *
     * @param config Configuration of OpenCms.
     * @exception ServletException Thrown when sevlet initalization fails.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
        String base = config.getInitParameter("opencms.home");
            System.err.println("BASE: " + config.getServletContext().getRealPath("/"));
            System.err.println("BASE2: " + System.getProperty("user.dir"));
        if(base == null || "".equals(base)) {
            System.err.println("No OpenCms home folder given. Trying to guess...");
            base = CmsMain.searchBaseFolder(config.getServletContext().getRealPath("/"));
            if(base == null || "".equals(base)) {
                throw new ServletException("OpenCms base folder could not be guessed. Please define init parameter \"opencms.home\" in servlet engine configuration.");
            }
        }
        base = CmsBase.setBasePath(base);        
        
        // Collect the configurations
        try {
            ExtendedProperties p = new ExtendedProperties(CmsBase.getPropertiesPath(true));

            // Change path to log file, if given path is not absolute
            String logFile = (String)p.get("log.file");
            if(logFile != null) {
                p.put("log.file", CmsBase.getAbsolutePath(logFile));
            }

            m_configurations = new Configurations(p);
        }
        catch(Exception e) {
            throw new ServletException(e.getMessage() + ".  Properties file is: " + CmsBase.getBasePath() + "opencms.properties");
        }

        // Initialize the logging
        A_OpenCms.initializeServletLogging(m_configurations);
        if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
            A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] Server Info: " + config.getServletContext().getServerInfo());
        }

        // initialize the redirect information
        int count = 0;
        String redirect;
        String redirectlocation;
        while((redirect = (String)m_configurations.getString(C_PROPERTY_REDIRECT + "." + count)) != null) {
            redirectlocation = (String)m_configurations.getString(C_PROPERTY_REDIRECTLOCATION + "." + count);
            redirectlocation = Utils.replace(redirectlocation, C_WEB_APP_REPLACE_KEY, CmsBase.getWebAppName());
            m_redirect.addElement(redirect);
            m_redirectlocation.addElement(redirectlocation);
            count++;
            if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
                A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] redirect-rule: " + redirect + " -> " + redirectlocation);
            }
        }
        m_clusterurl = (String)m_configurations.getString(C_CLUSTERURL, "");
        if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
            A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] Clusterurl: " + m_clusterurl);
        }
        
        try {
            // invoke the OpenCms
            m_opencms = new OpenCms(m_configurations);
        } catch(Exception exc) {
            throw new ServletException(Utils.getStackTrace(exc));
        }

        // initalize the session storage
        if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
            A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing session storage");
        }
        m_sessionStorage = new CmsCoreSession();
        if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
            A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCmsServlet] initializing... DONE");
        }
    }

    /**
     * This method handled the user authentification for each request sent to the
     * OpenCms. <p>
     *
     * User authentification is done in three steps:
     * <ul>
     * <li> Session Authentification: OpenCms stores all active sessions of authentificated
     * users in an internal storage. During the session authetification phase, it is checked
     * if the session of the active user is stored there. </li>
     * <li> HTTP Autheification: If session authentification fails, it is checked if the current
     * user has loged in using HTTP authentification. If this check is positive, the user account is
     * checked. </li>
     * <li> Default user: When both authentification methods fail, the current user is
     * set to the default (guest) user. </li>
     * </ul>
     *
     * @param req   The clints request.
     * @param res   The servlets response.
     * @return The CmsObject
     * @exception IOException Thrown if user autherization fails.
     */
    private CmsObject initUser(I_CmsRequest cmsReq, I_CmsResponse cmsRes) throws IOException {
        HttpSession session;
        String user = null;
        String group = null;
        Integer project = null;
        String loginParameter;

        // get the original ServletRequest and response
        HttpServletRequest req = (HttpServletRequest)cmsReq.getOriginalRequest();
        HttpServletResponse res = (HttpServletResponse)cmsRes.getOriginalResponse();
        CmsObject cms = new CmsObject();

        //set up the default Cms object
        try {
            m_opencms.initUser(cms, cmsReq, cmsRes, C_USER_GUEST, C_GROUP_GUEST, C_PROJECT_ONLINE_ID, m_sessionStorage);

            // check if a parameter "opencms=login" was included in the request.
            // this is used to force the HTTP-Authentification to appear.

⌨️ 快捷键说明

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