rssfeedmanager.java

来自「OpenCMS内容管理入门指南」· Java 代码 · 共 263 行

JAVA
263
字号
/*
 * This library is part of the code for the book: OpenCms for Developers
 *
 * Copyright (c) 2007, 2008 Dan Liliedahl
 *
 * 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.
 *
 * 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.deepthoughts.rss.admin;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.PageContext;

import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.collectors.I_CmsResourceCollector;
import org.opencms.i18n.CmsEncoder;
import org.opencms.jsp.Messages;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.OpenCms;
import org.opencms.publish.CmsPublishManager;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.I_CmsXmlContentValue;

import com.deepthoughts.rss.RssChannelDef;

public class RSSFeedManager {

	/** VFS path to the rss feed repository */
	protected static final String FEED_REPOSITORY_PATH = "/system/shared/rssfeeds/";

	/** Resource type ID for RSS Feeds */
	protected static final int RSS_RESOURCE_TYPE_ID = 3001;

	/** Schema location */
	protected static final String RSS_SCHEMA = "/system/modules/com.deepthoughts.rss/schemas/rsschanneldef.xsd";
	
	/** Reference to the CmsObject */
	protected CmsObject m_cms;
	
	/**
	 * Factory method to return the instance of the RSS Feed Manager
	 * 
	 * @return RSSFeedManager instance
	 */
	public static RSSFeedManager getFeedManager(CmsObject cms) {
		return new RSSFeedManager(cms);
	}
	
	/**
	 * Default constructor
	 */
	public RSSFeedManager(CmsObject cms) {
		m_cms = cms;
	}

	/**
	 * Retrieves the path to the RSS Feed repository
	 * @return String with path to RSS feed base location
	 */
	public static String getFeedRepositoryPath() {
		return RSSFeedManager.FEED_REPOSITORY_PATH;
	}

	/**
	 * Retrieves the full name of the feed, including its location in the repository
	 * @param Feed Name of the feed
	 * @return full path name to the feed
	 */
	public static String getFullName(String Feed) {
		return getFeedRepositoryPath() + Feed;
	}
	
	/**
	 * Returns a list of CmsResources of the Feed definitions
	 * 
	 * @return List of CmsResources of type RSSChannelDef
	 */
	public List getChannels () {
    	// Use the collector to obtain a list of resources
    	String collectorName = "allInFolderDateReleasedDesc";
        try {
            // now collect the resources
            I_CmsResourceCollector collector = OpenCms.getResourceManager().getContentCollector(collectorName);
            if (null == collector) {
                throw new CmsException(Messages.get().container(Messages.ERR_COLLECTOR_NOT_FOUND_1, collectorName));
            }
            // get list of feeds in the repository
            List collectorResult = collector.getResults(m_cms, collectorName, 
            		FEED_REPOSITORY_PATH + "|" + Integer.toString(RSSFeedManager.RSS_RESOURCE_TYPE_ID));
            return collectorResult;
        } catch (CmsException e) {
			e.printStackTrace();
        }
    	return null;
	}

	/**
	 * Removes the specified RSS Channel. If this method fails the error is logged and silently ignored.
	 * 
	 * @param Channel the VFS path/name of the RSS Channel to remove
	 */
	public void deleteChannel(String Channel) {
		try {
			String resName = RSSFeedManager.getFullName(Channel);
			getLock(resName);
			// ensure resource is locked
            // delete it
			m_cms.deleteResource(RSSFeedManager.getFullName(Channel), CmsResource.DELETE_PRESERVE_SIBLINGS);
		} catch (CmsException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Saves the specified RssChannelDef to the VFS or updates it if it already exists
	 * @param Channel RssChannelDef to save to the VFS
	 */
	public void saveOrUpdateChannel(PageContext ctx, RssChannelDef Channel) {
    	try {
    		String resName = RSSFeedManager.getFullName(Channel.getFilename());

    		// if it exists then read the content otherwise create a new one
    		CmsXmlContent xmlContent;
    		boolean bExists;
    		try {
    			CmsResource res = m_cms.readFile(resName);
    			bExists = true;
    			xmlContent = CmsXmlContentFactory.unmarshal(m_cms, res, ctx.getRequest());
    		} catch (CmsException e) {
    			bExists = false;
        		// get the schema definition
                CmsXmlContentDefinition contentDefinition = 
                	CmsXmlContentDefinition.unmarshal(m_cms, RSS_SCHEMA);

                // create and instance of the XML content
                xmlContent = CmsXmlContentFactory.createDocument(m_cms, 
       				m_cms.getRequestContext().getLocale(),
       				OpenCms.getSystemInfo().getDefaultEncoding(),
       				contentDefinition);
    		}
    		
            // set the field values into the content
	    	addOrUpdateFieldIfNonNull(xmlContent, "Title", Channel.getTitle());
	    	addOrUpdateFieldIfNonNull(xmlContent, "Description", Channel.getDescription());
	    	addOrUpdateFieldIfNonNull(xmlContent, "Copyright", Channel.getCopyright());
	    	addOrUpdateFieldIfNonNull(xmlContent, "Author", Channel.getAuthor());
	    	addOrUpdateFieldIfNonNull(xmlContent, "PublishDate", Long.toString(Channel.getPublishedDate()));
	    	addOrUpdateFieldIfNonNull(xmlContent, "Image", Channel.getImage());
	    	addOrUpdateFieldIfNonNull(xmlContent, "ImageTitle", Channel.getImageTitle());

            // set the title and description properties            
            List properties = new ArrayList(2);
            CmsProperty prop = new CmsProperty();
            prop.setName(CmsPropertyDefinition.PROPERTY_TITLE);
            prop.setValue(Channel.getTitle(), CmsProperty.TYPE_INDIVIDUAL);
            properties.add(prop);
            prop = new CmsProperty();
            prop.setName(CmsPropertyDefinition.PROPERTY_DESCRIPTION);
            prop.setValue(Channel.getDescription(), CmsProperty.TYPE_INDIVIDUAL);
            properties.add(prop);

            // now we save the changes to the content
	    	String decodedContent = xmlContent.toString();
	        try {
	        	if (bExists) {
	        		CmsFile docFile = xmlContent.getFile();
		        	docFile.setContents(decodedContent.getBytes(CmsEncoder.lookupEncoding("UTF-8", "UTF-8")));
		    		getLock(resName);
			        m_cms.writeFile(docFile);
			        m_cms.unlockResource(resName);
	        	} else {
	        		m_cms.createResource(resName, RSS_RESOURCE_TYPE_ID,
        				decodedContent.getBytes(CmsEncoder.lookupEncoding("UTF-8", "UTF-8")), properties);
	        	}
	        } catch (UnsupportedEncodingException e) {
				e.printStackTrace();
	        }
		} catch (CmsIllegalArgumentException e) {
			e.printStackTrace();
		} catch (CmsException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Publishes the specified RssChannelDef to the Online project
	 * @param Channel RssChannelDef to save to the VFS
	 */
	public void publishChannel(String Channel) {
		try {
			// publish the Channel
	        CmsPublishManager pm = OpenCms.getPublishManager();
	        pm.publishResource(m_cms, RSSFeedManager.getFullName(Channel));
		} catch (Exception e) {
			// print out stack trace in case of error
			e.printStackTrace();
		}
	}
	
	/**
	 * Obtain a lock on the resource to perform certain operations
	 * 
	 * @param Channel Resource name to obtain lock of
	 * @throws CmsException 
	 */
	protected void getLock(String Channel) throws CmsException {
		CmsLock lock = m_cms.getLock(Channel);
        if (!m_cms.getLock(Channel).isUnlocked()) {
            // steal lock
            m_cms.changeLock(Channel);
        } else {
            // lock resource to current user
            m_cms.lockResource(Channel);
        }
	}
	
	/**
	 * Adds a field to the xml content if it is not present, or updates the existing field it
	 * it is present
	 * 
	 * @param iContent CmsXmlContent instance to update
	 * @param Fieldname Name of the field to update
	 * @param newVal Value to place into the field
	 */
	protected void addOrUpdateFieldIfNonNull(CmsXmlContent iContent, String Fieldname, String newVal) {
		// first try to read back the value
		I_CmsXmlContentValue curVal = iContent.getValue(Fieldname, m_cms.getRequestContext().getLocale());
    	if (null != curVal) {
    		// field is already there so update it
    		curVal.setStringValue(m_cms, newVal);
    	} else {
    		// no existing field, only set one if a value is provided
    		if (null != newVal) {
    			curVal = iContent.addValue(m_cms, Fieldname, m_cms.getRequestContext().getLocale(), 0);
	    		curVal.setStringValue(m_cms, newVal);
    		}
    	}
	}
	
}

⌨️ 快捷键说明

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