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

📄 filestaticpagedao.java

📁 pebble-blog 博客源码博客源码博客源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package net.sourceforge.pebble.dao.file;import net.sourceforge.pebble.dao.PersistenceException;import net.sourceforge.pebble.dao.StaticPageDAO;import net.sourceforge.pebble.domain.*;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.xml.sax.ErrorHandler;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.helpers.DefaultHandler;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import javax.xml.transform.*;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.io.*;import java.text.SimpleDateFormat;import java.util.*;public class FileStaticPageDAO implements StaticPageDAO {  /**   * the log used by this class   */  private static Log log = LogFactory.getLog(FileStaticPageDAO.class);  private DocumentBuilder builder;  public FileStaticPageDAO() {    try {      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      factory.setValidating(false);      factory.setNamespaceAware(true);      factory.setIgnoringElementContentWhitespace(true);      factory.setIgnoringComments(true);      builder = factory.newDocumentBuilder();      builder.setErrorHandler(new ErrorHandler() {        public void warning(SAXParseException e) throws SAXException {          log.warn(e);          throw e;        }        public void error(SAXParseException e) throws SAXException {          log.error(e);          throw e;        }        public void fatalError(SAXParseException e) throws SAXException {          log.fatal(e);          throw e;        }      });    } catch (Exception e) {      e.printStackTrace();    }  }  /** the date/time format used when persisting dates */  static final String OLD_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss z";  static final String NEW_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss:S Z";  static final String REGEX_FOR_YEAR = "\\d\\d\\d\\d";  /**   * Loads the static pages for a given blog.   *   * @param blog the owning Blog instance   * @return a Collection of StaticPage instances   * @throws net.sourceforge.pebble.dao.PersistenceException   *          if static pages cannot be loaded   */  public Collection<StaticPage> loadStaticPages(Blog blog) throws PersistenceException {    List<StaticPage> list = new ArrayList<StaticPage>();    File root = new File(blog.getRoot(), "pages");    File files[] = root.listFiles(new BlogEntryFilenameFilter());    if (files != null) {        for (File file : files) {            list.add(loadStaticPage(blog, file));        }    }    return list;  }  /**   * Loads a specific static page.   *   * @param blog   the owning Blog   * @param pageId the page ID   * @return a StaticPage instance   * @throws net.sourceforge.pebble.dao.PersistenceException   *          if the static page cannot be loaded   */  public StaticPage loadStaticPage(Blog blog, String pageId) throws PersistenceException {    File path = new File(getPath(blog, pageId));    File file = new File(path, pageId + ".xml");    return loadStaticPage(blog, file);  }  /**   * Stores the specified static page.   *   * @param staticPage the static page to store   * @throws net.sourceforge.pebble.dao.PersistenceException   *          if something goes wrong storing the static page   */  public void storeStaticPage(StaticPage staticPage) throws PersistenceException {    File outputDir = new File(getPath(staticPage.getBlog(), staticPage.getId()));    if (!outputDir.exists()) {      outputDir.mkdirs();    }    File outputFile = new File(outputDir, staticPage.getId() + ".xml");    storeStaticPage(staticPage, outputFile);  }  /**   * Stores a static page to the specified file.   *   * @param staticPage    the StaticPage that is being stored   * @param destination the File pointing to the destination   * @throws PersistenceException if something goes wrong storing the static page   */  private void storeStaticPage(StaticPage staticPage, File destination) throws PersistenceException {    File backupFile = new File(destination.getParentFile(), destination.getName() + ".bak");    try {      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      factory.setValidating(false);      factory.setNamespaceAware(true);      factory.setIgnoringElementContentWhitespace(true);      factory.setIgnoringComments(true);      DocumentBuilder builder = factory.newDocumentBuilder();      Document doc = builder.newDocument();      Element root = doc.createElement("staticPage");      doc.appendChild(root);      Element titleNode = doc.createElement("title");      Element subtitleNode = doc.createElement("subtitle");      Element bodyNode = doc.createElement("body");      Element dateNode = doc.createElement("date");      Element stateNode = doc.createElement("state");      Element authorNode = doc.createElement("author");      Element staticNameNode = doc.createElement("staticName");      root.appendChild(titleNode);      root.appendChild(subtitleNode);      root.appendChild(bodyNode);      root.appendChild(dateNode);      root.appendChild(stateNode);      root.appendChild(authorNode);      root.appendChild(staticNameNode);      if (staticPage.isAggregated()) {        Element permalinkNode = doc.createElement("originalPermalink");        permalinkNode.appendChild(doc.createTextNode(staticPage.getOriginalPermalink()));        root.appendChild(permalinkNode);      }      titleNode.appendChild(doc.createTextNode(staticPage.getTitle()));      subtitleNode.appendChild(doc.createTextNode(staticPage.getSubtitle()));      bodyNode.appendChild(doc.createCDATASection(staticPage.getBody()));      if (staticPage.getAuthor() != null) {        authorNode.appendChild(doc.createTextNode(staticPage.getAuthor()));      }      if (staticPage.getName() != null) {        staticNameNode.appendChild(doc.createTextNode(staticPage.getName()));      }      SimpleDateFormat sdf = new SimpleDateFormat(NEW_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);      sdf.setTimeZone(staticPage.getBlog().getTimeZone());      dateNode.appendChild(doc.createTextNode(sdf.format(staticPage.getDate())));      stateNode.appendChild(createTextNode(doc, staticPage.getState().getName()));      // write the XMl to a String, and then write this string to a file      // (if the XML format fails, we don't corrupt the file)      StringWriter sw = new StringWriter();      Source source = new DOMSource(doc);      Result result = new StreamResult(sw);      Transformer xformer = TransformerFactory.newInstance().newTransformer();      xformer.setOutputProperty(OutputKeys.METHOD, "xml");      xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");      xformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");      xformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "body");      xformer.setOutputProperty(OutputKeys.INDENT, "yes");      xformer.transform(source, result);      // now take a backup of the correct file      if (destination.exists() && destination.length() > 0) {        log.debug("Backing up to " + backupFile.getAbsolutePath());        destination.renameTo(backupFile);      }      log.debug("Saving to " + destination.getAbsolutePath());      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destination), "UTF-8"));      bw.write(sw.getBuffer().toString());      bw.flush();      bw.close();    } catch (Exception e) {      log.error(e.getMessage(), e);      e.printStackTrace();      throw new PersistenceException(e.getMessage());    }  }  /**   * Removes the specified static page.   *   * @param staticPage the static page to remove   * @throws net.sourceforge.pebble.dao.PersistenceException   *          if something goes wrong removing the page   */  public void removeStaticPage(StaticPage staticPage) throws PersistenceException {    File path = new File(getPath(staticPage.getBlog(), staticPage.getId()));    File file = new File(path, staticPage.getId() + ".xml");    log.debug("Removing " + staticPage.getGuid());    boolean success = file.delete();    if (!success) {      throw new PersistenceException("Deletion of static page" + staticPage.getGuid() + " failed");    }  }  /**   * Loads a blog entry from the specified file.   *   * @param source    the File pointing to the source   * @throws net.sourceforge.pebble.dao.PersistenceException   *          if the blog entry can't be loaded   */  private StaticPage loadStaticPage(Blog blog, File source) throws PersistenceException {    if (source.exists()) {      log.debug("Loading static page from " + source.getAbsolutePath());      StaticPage staticPage = new StaticPage(blog);      try {        DefaultHandler handler = new StaticPageHandler(staticPage);        SAXParserFactory saxFactory = SAXParserFactory.newInstance();        saxFactory.setValidating(false);        saxFactory.setNamespaceAware(true);        SAXParser parser = saxFactory.newSAXParser();        parser.parse(source, handler);      } catch (Exception e) {        log.error(e.getMessage(), e);        e.printStackTrace();        throw new PersistenceException(e.getMessage());      }      return staticPage;    } else {      return null;    }  }  /**   * Stores the specified blog entry.   *   * @param blogEntry the blog entry to store   * @throws net.sourceforge.pebble.dao.PersistenceException if something goes wrong storing the entry   */  public void storeBlogEntry(BlogEntry blogEntry) throws PersistenceException {    File outputDir = new File(getPath(blogEntry.getBlog(), blogEntry.getId()));    if (!outputDir.exists()) {      outputDir.mkdirs();    }    File outputFile = new File(outputDir, blogEntry.getId() + ".xml");    storeBlogEntry(blogEntry, outputFile);  }  /**   * Stores a blog entry to the specified file.   *   * @param blogEntry   the BlogEntry that is being stored

⌨️ 快捷键说明

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