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

📄 cmsjsploader.java

📁 内容管理
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
    } 

    // ---------------------------- Static export related stuff
    
    /**
     * Checks if the request parameter C_EXPORT_PARAM is set, if so sets the CmsObject 
     * working mode to C_MODUS_EXPORT.
     * 
     * @param cms provides the current cms context
     * @param req the current request 
     * @return int the mode previously set in the CmsObject
     */
    private int exportCheckMode(CmsObject cms, HttpServletRequest req) {
        int oldMode = cms.getMode();
        String exportUri = req.getParameter(C_EXPORT_PARAM); 
        if (exportUri != null) {
            if (! exportUri.equals(cms.getRequestContext().getUri())) {
                // URI is not the same, so this is a sub - element
                cms.getRequestContext().setUri(exportUri);
            }
            cms.setMode(CmsObject.C_MODUS_EXPORT);
        }   
        // check body
        String body = req.getParameter(C_EXPORT_BODY);
        if (body != null) {
            cms.getRequestContext().setAttribute(I_CmsConstants.C_XML_BODY_ELEMENT, body);
        }
        // check encoding
        String encoding = req.getParameter(C_EXPORT_ENCODING);
        if (encoding != null) {
            cms.getRequestContext().setEncoding(encoding);
        }
        return oldMode;     
    }

    /**
     * Restores the mode stored in the <code>oldMode</code> paameter to the CmsObject.
     * 
     * @param cms provides the current cms context
     * @param oldMode the old mode to restore in the CmsObject
     */
    private void exportResetMode(CmsObject cms, int oldMode) {
        cms.setMode(oldMode);
    }

    /**
     * Returns the links found in the currently processed page as response headers,
     * so that the static export can pick them up later.
     *
     * @param cms provides the current cms context
     * @param res the response to set the headers in
     */
    private void exportSetLinkHeader(CmsObject cms, HttpServletResponse res) {
        // get the links found on the page from the current request context
        Vector v = cms.getRequestContext().getLinkVector();
        // making the vector a set removes the duplicate entries
        Set s = new HashSet(v);
        StringBuffer links = new StringBuffer(s.size() * 64);
        Iterator i = s.iterator();
        // build a string out of the found links
        while (i.hasNext()) {
            links.append(Encoder.encode((String)i.next()));
            if (i.hasNext()) links.append(C_EXPORT_HEADER_SEP);
        }
        // set the export header and we are finished
        res.setHeader(C_EXPORT_HEADER, new String(links));
    }
    
    /**
     * Perform an export of the requested JSP page.<p>
     * 
     * The export of a JSP is done in the following way:
     * <ul>
     * <li>A HttpURLConnection is openend to the address configured in the runtime property with
     * the name {@link #C_LOADER_JSPEXPORTURL}, which usually should be the current OpenCms server.
     * <li>The URI of the <code>file</code> is appended to the connection as path information, so
     * this will be the page requested and exported.
     * <li>All current request parameters are encoded and also added to the request as parameters.
     * <li>The currently requested URI is also appended as value of the special parameter {@link
     * #C_EXPORT_PARAM}.
     * <li>When processing this special request, the mode of the <code>CmsObject</code> will be
     * set to <code>C_MODUS_EXPORT</code>, which is the required mode if you want to generate
     * the result for an export.
     * <li>All links found while processing the exported JSP will be written in a special header
     * of the response, called {@link #C_EXPORT_HEADER}.
     * <li>The response result will be checked for the headers and all links found will be added to
     * the link vector of the currently processed page.
     * <li>The content of the resonse will be read into a byte array and returned as result of this
     * call.
     * </ul>
     *  
     * @param cms provides the current cms context
     * @param file the JSP file requested
     * @return the contents of the JSP page for the export
     */
    private byte[] exportJsp(CmsObject cms, CmsFile file) throws CmsException {
        
        // check if we are properly initialized
        if (m_jspExportUrl == null) {
            throw new CmsException("JSP export URL not set, can not export JSP", CmsException.C_FLEX_LOADER);
        }
        
        ByteArrayOutputStream bytes = null;        
        CmsRequestContext context = cms.getRequestContext();
        
        // generate export URL
        StringBuffer exportUrl = new StringBuffer(m_jspExportUrl); 
        exportUrl.append(file.getAbsolutePath());
        exportUrl.append("?");
        
        // add parameters to export call
        Enumeration params = context.getRequest().getParameterNames();
        while (params.hasMoreElements()) {
            String key = (String)params.nextElement();
            String values[] = (String[])context.getRequest().getParameterValues(key);
            for (int i=0; i<values.length; i++) {
                exportUrl.append(key);
                exportUrl.append("=");
                exportUrl.append(Encoder.encode(values[i]));
                exportUrl.append("&");
            }
        }
        // add the export parameter to the request
        exportUrl.append(C_EXPORT_PARAM);
        exportUrl.append("=");
        exportUrl.append(cms.getRequestContext().getUri());
        // add the original requested body file to the request
        String body = (String)cms.getRequestContext().getAttribute(I_CmsConstants.C_XML_BODY_ELEMENT);
        if (body != null) {
            exportUrl.append("&");
            exportUrl.append(C_EXPORT_BODY);
            exportUrl.append("=");
            exportUrl.append(Encoder.encode(body));            
        }
        // add the encoding used for the output page to the request
        String encoding = cms.getRequestContext().getEncoding();
        exportUrl.append("&");
        exportUrl.append(C_EXPORT_ENCODING);
        exportUrl.append("=");
        exportUrl.append(Encoder.encode(encoding));        
        
        if (DEBUG > 2) System.err.println("CmsJspLoader.exportJsp(): JSP export URL is " + exportUrl);

        // perform the export with an URLConnection
        URL export;
        HttpURLConnection urlcon;
        DataInputStream input;
                
        try {
            export = new URL(new String(exportUrl));
            urlcon = (HttpURLConnection) export.openConnection();
            // set request type to POST
            urlcon.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false);
            // input and output stream
            input = new DataInputStream(urlcon.getInputStream());
            bytes = new ByteArrayOutputStream(urlcon.getContentLength()>0?urlcon.getContentLength():1024);
        } catch (Exception e) {
            // all exceptions here will be IO related
            throw new CmsException("IO related error while exporting JSP for URI " + cms.getRequestContext().getUri(), 
                CmsException.C_FLEX_LOADER, e);
        }
        
        // check if links are present in the exported page 
        String cmslinks = urlcon.getHeaderField(C_EXPORT_HEADER);
        if (cmslinks != null) {
            // add all the links to the current cms context
            StringTokenizer tok = new StringTokenizer(cmslinks, C_EXPORT_HEADER_SEP);
            while (tok.hasMoreTokens()) {
                String link = Encoder.decode(tok.nextToken(), "UTF-8", true);
                cms.getRequestContext().addLink(link);
                if (DEBUG > 3) System.err.println("CmsJspLoader.exportJsp(): Extracted link " + link);
            }
        }
        // now read the page content and write it to the byte array
        try {
            int b;
            while ((b = input.read()) > 0) {
                bytes.write(b);
            }
        } catch (IOException e) {
            throw new CmsException("IO error writing bytes to buffer exporting JSP for URI " + cms.getRequestContext().getUri(),
                CmsException.C_FLEX_LOADER, e);            
        }

        return bytes.toByteArray();
    }

    // ---------------------------- Implementation of interface com.opencms.flex.I_CmsResourceLoader    
    
    /** Destroy this ResourceLoder, this is a NOOP so far.  */
    public void destroy() {
        // NOOP
    }
    
    /**
     * Return a String describing the ResourceLoader,
     * which is <code>"The OpenCms default resource loader for JSP"</code>
     * 
     * @return a describing String for the ResourceLoader 
     */
    public String getResourceLoaderInfo() {
        return "The OpenCms default resource loader for JSP";
    }
    
    /** 
     * Initialize the ResourceLoader,
     * here the configuration for the JSP repository (directories used) is set.
     *
     * @param openCms An OpenCms object to use for initalizing.
     */
    public void init(A_OpenCms openCms) {
        m_jspRepository = com.opencms.boot.CmsBase.getBasePath();
        if (m_jspRepository.indexOf("WEB-INF") >= 0) {
            // Should always be true, just make sure we don't generate an exception in untested environments
            m_jspRepository = m_jspRepository.substring(0, m_jspRepository.indexOf("WEB-INF")-1);
        }
        source.org.apache.java.util.Configurations c = openCms.getConfiguration();
        m_jspWebAppRepository = c.getString("flex.jsp.repository", "/WEB-INF/jsp");
        m_jspRepository += m_jspWebAppRepository.replace('/', File.separatorChar);
        if (! m_jspRepository.endsWith(File.separator)) m_jspRepository += File.separator;
        if (DEBUG > 0) System.err.println("JspLoader: Setting jsp repository to " + m_jspRepository);
        // Get the cache from the runtime properties
        m_cache = (CmsFlexCache)A_OpenCms.getRuntimeProperty(C_LOADER_CACHENAME);
        // Get the export URL from the runtime properties
        m_jspExportUrl = (String)A_OpenCms.getRuntimeProperty(C_LOADER_JSPEXPORTURL);
        if (I_CmsLogChannels.C_LOGGING && A_OpenCms.isLogging(I_CmsLogChannels.C_FLEX_LOADER)) {
            A_OpenCms.log(I_CmsLogChannels.C_FLEX_LOADER, "Initialized!");        
            A_OpenCms.log(I_CmsLogChannels.C_FLEX_LOADER, "JSP repository (absolute path): " + m_jspRepository);        
            A_OpenCms.log(I_CmsLogChannels.C_FLEX_LOADER, "JSP repository (web application path): " + m_jspWebAppRepository);              
            A_OpenCms.log(I_CmsLogChannels.C_FLEX_LOADER, "JSP export URL: " + m_jspExportUrl);
        }
        // Get the "error pages are commited or not" flag from the runtime properties
        Boolean errorPagesAreNotCommited = (Boolean)A_OpenCms.getRuntimeProperty(C_LOADER_ERRORPAGECOMMIT);
        if (errorPagesAreNotCommited != null) m_errorPagesAreNotCommited = errorPagesAreNotCommited.booleanValue();
    }
    
    /**
     * Set's the JSP export URL.<p>
     * 
     * This is required after <code>init()</code> called if the URL was not set in <code>opencms.
     * properties</code>.
     * 
     * @param url the JSP export URL
     */
    public static void setJspExportUrl(String value) {
        m_jspExportUrl = value;

⌨️ 快捷键说明

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