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

📄 blogjsptemplate.java

📁 OpenCMS内容管理入门指南
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
     * @return count of blog entries in the folder
     */
    public int getBlogCount(CmsResource res) {
    	try {
    		// count only the entries that are blogs and exclude any temp files
            CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(BLOG_RESOURCE_TYPEID).addExcludeFlags(
                    CmsResource.FLAG_TEMPFILE);    		
			List lstBlogs = getCmsObject().readResources(getCmsObject().getSitePath(res), filter);
			return lstBlogs.size();
		} catch (CmsException e) {
			e.printStackTrace();
			return 0;
		}
    }
    
    /**
     * Test to see if there are more blogs to be displayed.
     * 
     * @return true if more blogs exist, else false
     */
    public boolean hasMoreBlogs() {
    	if (null != m_iContent) {
    		try {
				return m_iContent.hasMoreContent();
			} catch (JspException e) {
				return false;
			}
    	}
    	return false;
    }

    /**
     * This method builds a link to the current file item in the collection.  The passed
     * text is used for the link text.
     * 
     * @param LinkText Text to use for the link
     * @return HTML with HREF link to the current file or NULLSTR if no collection
     */
    public String linkToCurrentItem(String LinkText) {
    	if (null != m_iContent) {
	    	// get resource path
	    	String strFile = m_iContent.getResourceName();
	
	    	// build the link
	    	return "<a href='" + link(strFile) + "'>" + LinkText + "</a>";
    	}
    	return NULLSTR;
    }

    /**
     * Returns the content from a data field
     * 
     * @param Fieldname	Fieldname to retrieve content from
     * 
     * @return Field content or empty string ("") if no value for field
     */
    public String getField(String Fieldname) {
    	if (null != m_iContent) {
    		return contentshow(m_iContent, Fieldname);
    	}
    	return NULLSTR;
    }

    /**
     * Returns the HTML for the blog image if it exists.  The image will be aligned according to the Alignment field
     * in the BlogEntry. This method uses the CmsImageScaler to scale the image to the appropriate size.
     * 
     * @param Width	width of the image
     * @return HTML with the necessary IMG and align tags to display the image
     */
    public String getBlogImage(int Height) {
    	if (fieldExists(FIELD_IMAGE)) {
    		CmsImageScaler scaler = new CmsImageScaler();
    		scaler.setHeight(Height);
    		HashMap<String, String> attributes = new HashMap<String, String>();
    		String strAlign = getField(FIELD_ALIGNMENT);
    		attributes.put("align", strAlign);
    		attributes.put("height", Integer.toString(Height));
    		return img(getField(FIELD_IMAGE), scaler, attributes);
    	}
    	return NULLSTR;
    }

    /**
     * Determines if the given content field contains data
     * 
     * @param Fieldname	Name of the content field to check
     * 
     * @return true if data exists in field, else false
     */
    protected boolean fieldExists(String Fieldname) {
    	return CmsJspTagContentCheck.contentCheckTagAction(Fieldname, null,
    	        true, false, m_iContent.getXmlDocument(), getRequestContext().getLocale());
    }

    /**
     * Returns the list of topics added to the blog
     * 
     * @return String with a comma separated list of categories or NULLSTR
     */
    public String showTopics() {
    	// StringBuffer to hold the response
    	StringBuffer sbCategories = new StringBuffer(NULLSTR);
    	
    	// get list of categories
    	I_CmsXmlContentContainer iCategories = contentloop(m_iContent, FIELD_TOPIC);

    	boolean bFirst = true;
    	try {
			while (iCategories.hasMoreContent()) {
				if (false == bFirst) {
					// after first on we can append a comma
					sbCategories.append(",&nbsp;");
				} else {
					// no longer the first one
					bFirst = false;
				}
				// add the category
				sbCategories.append(this.contentshow(iCategories));
			}
		} catch (JspException e) {
			e.printStackTrace();
		}
		
    	return sbCategories.toString();
    }

    /**
     * This method returns a url for adding a comment to the current blog item. For
     * users that are not logged in or registered a url to the registration page is
     * returned instead.
     * 
     * @return String with URL
     */
    public String getAddCommentUrl() {
    	CmsUser user = getRequestContext().currentUser();
    	String OU = getRequestContext().getOuFqn();
    	if (user.isGuestUser() || 
   			user.getName().equals("Admin") ||
   			user.getName().equals(OU + "BlogAdmin") ) {
    		return link(URL_REGISTER + "?blog=" + m_iContent.getResourceName());
    	} else {
    		return link(URL_ADD_COMMENT + "?blog=" + m_iContent.getResourceName());
    	}
    }

    /**
     * Returns any message associated with the registration action
     * @return
     */
    public String getRegisterActionMessage() {
    	return (String) getRequest().getAttribute("REG_ERROR");
    }

    /**
     * Sets a message associated with the registration action
     * @param Message
     */
    protected void setRegisterActionMessage(String Message) {
    	m_strRegisterMessage = Message;
    	getRequest().setAttribute("REG_ERROR", Message);
    }

    /**
     * Perform the 'Add Comment' action by adding a new comment to the blog entry.
     * 
     * @return action code
     */
    public int addCommentAction() {
    	// was anything posted?
		String strComment = getRequest().getParameter("comment");
		if (null != strComment) {
			// yes, now load the blog and add the comment
			try {
				m_iContent.hasMoreContent();
				// add the comment
				addCommentToBlog(m_iContent.getResourceName(), strComment);
				
				// publish the blog
				publishBlog(m_iContent.getResourceName());
				
				return FORMACTION_OK;
				
			} catch (JspException e) {
				e.printStackTrace();
			}
		}
    	// show the action form
    	return FORMACTION_SHOWFORM;
    }

    /**
     * Updates the passed blog entry by adding a comment to the nested comment field.
     * This works only for the offline blog entry, the change must be published for
     * it to be available to online viewers.
     * 
     * @param Blog the VFS path to the blog
     * @param strComment the comment text to add to the blog
     */
    protected void addCommentToBlog(String Blog, String strComment) {
    	
		try {
			// adding content must be done in the Offline project
			getCmsObject().getRequestContext().setCurrentProject(getCmsObject().readProject("Offline"));
    		    		
			// first we read the blog to count the number of existing comments in it. We
    		// need to know in order to be able to add another comment to the end
	    	CmsFile docFile = m_iContent.getXmlDocument().getFile();
			CmsXmlContent content = CmsXmlContentFactory.unmarshal(getCmsObject(), docFile);
	    	int nComments = 1;
    		List l = content.getValues("Comment", getRequestContext().getLocale());
    		nComments = l.size();
	    	
			// Now we can add the nested Comment at the end of the list
	    	I_CmsXmlContentValue val = content.addValue(getCmsObject(), FIELD_COMMENT,
	    			getRequestContext().getLocale(), nComments);

	    	// once the comment is added we can set the individual fields into it
	    	nComments++;
	    	String strCommentNdx = "[" + Integer.toString(nComments) + "]";
	    	val = content.getValue(FIELD_COMMENT + strCommentNdx + "/User[1]", 
	    			getRequestContext().getLocale());
	    	val.setStringValue(getCmsObject(), getRequestContext().currentUser().getName());
	    	
	    	// set date/time
	    	val = content.getValue(FIELD_COMMENT + strCommentNdx + "/Date[1]", 
	    			getRequestContext().getLocale());
	    	val.setStringValue(getCmsObject(), Long.toString(System.currentTimeMillis()));
	    	
	    	// set comment
	    	val = content.getValue(FIELD_COMMENT + strCommentNdx + "/Comment[1]", 
	    			getRequestContext().getLocale());
	    	val.setStringValue(getCmsObject(), strComment);
 	
	    	// now we save the changes to the VFS
	    	String decodedContent = content.toString();
	        try {
	        	docFile.setContents(decodedContent.getBytes(CmsEncoder.lookupEncoding("UTF-8", "UTF-8")));
	        } catch (UnsupportedEncodingException e) {
				e.printStackTrace();
	        }
	        String strFile = m_iContent.getResourceName();         	
	        getCmsObject().lockResource(strFile);
	        getCmsObject().writeFile(docFile);
	        getCmsObject().unlockResource(strFile);

		} catch (CmsXmlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CmsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// switch back to online project
        try {
			getCmsObject().getRequestContext().
				setCurrentProject(getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID));
		} catch (CmsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    
    }


    /**
     * Publishes the blog from the offline to the online project
     * 
     * @param Blog VFS resource path of blog to be published
     */
    protected void publishBlog(String Blog) {

    	// remember the current user
    	CmsUser user = getRequestContext().currentUser();
    	
		try {
			// login the publish user we created for publishing comments
			getCmsObject().loginUser(USR_DEEPTHOUGHTS_COMMENT_PUBLISHER, USR_DEEPTHOUGHTS_COMMENT_PUBLISHER_PW);
			
			// switch to the offline project
			getCmsObject().getRequestContext().setCurrentProject(getCmsObject().
					readProject("Offline"));

			// publish the Blog resource with the changes
	        CmsPublishManager pm = OpenCms.getPublishManager();
	        pm.publishResource(getCmsObject(), Blog);
		} catch (CmsException e) {
			// print out stack trace in case of error
			e.printStackTrace();
		} catch (Exception e) {
			// print out stack trace in case of error
			e.printStackTrace();
			
		} finally {
	        try {
		        // restore original user and switch to online
				OpenCms.getSessionManager().switchUser(getCmsObject(), getRequest(), user);
		        getCmsObject().getRequestContext().
		        	setCurrentProject(getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID));
			} catch (CmsException e) {
				// something went wrong
				e.printStackTrace();
				// if this fails we fall back to logging out and reverting to guest
				logout();
			}
	        
		}
    }
    
    /**
     * logout the user
     *
     */
    public void logout() {

⌨️ 快捷键说明

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