fileblogentrydao.java

### File Source: fileblogentrydao.java

         1  package net.sourceforge.pebble.dao.file;
         2
         3  import net.sourceforge.pebble.dao.BlogEntryDAO;
         4  import net.sourceforge.pebble.dao.PersistenceException;
         5  import net.sourceforge.pebble.domain.*;
         6  import org.apache.commons.logging.Log;
         7  import org.apache.commons.logging.LogFactory;
         8  import org.w3c.dom.Document;
         9  import org.w3c.dom.Element;
        10  import org.w3c.dom.Node;
        11  import org.xml.sax.helpers.DefaultHandler;
        12
        13  import javax.xml.parsers.DocumentBuilder;
        14  import javax.xml.parsers.DocumentBuilderFactory;
        15  import javax.xml.parsers.SAXParser;
        16  import javax.xml.parsers.SAXParserFactory;
        17  import javax.xml.transform.*;
        18  import javax.xml.transform.dom.DOMSource;
        19  import javax.xml.transform.stream.StreamResult;
        20  import java.io.*;
        21  import java.text.DateFormat;
        22  import java.text.SimpleDateFormat;
        23  import java.util.*;
        24
        25  public class FileBlogEntryDAO implements BlogEntryDAO {
        26
        27    /** timezone to use for calculating paths on disk, etc */
               /*
        P/P     *  Method: net.sourceforge.pebble.dao.file.FileBlogEntryDAO__static_init
                *
                *  Postconditions:
                *    init'ed(GMT)
                *    init'ed(log)
                */
        28    private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
        29
        30    /**
        31     * the log used by this class
        32     */
        33    private static Log log = LogFactory.getLog(FileBlogEntryDAO.class);
        34
               /*
        P/P     *  Method: void net.sourceforge.pebble.dao.file.FileBlogEntryDAO()
                */
        35    public FileBlogEntryDAO() {
        36    }
        37
        38    /** the date/time format used when persisting dates */
        39    static final String OLD_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss z";
        40    static final String NEW_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss:S Z";
        41    static final String REGEX_FOR_YEAR = "\\d\\d\\d\\d";
        42
        43    /**
        44     * Loads a specific blog entry.
        45     *
        46     * @param blogEntryId   the blog entry ID
        47     * @return a BlogEntry instance
        48     * @throws net.sourceforge.pebble.dao.PersistenceException
        49     *          if the specified blog entry cannot be loaded
        50     */
        51    public BlogEntry loadBlogEntry(Blog blog, String blogEntryId) throws PersistenceException {
                 /*
        P/P       *  Method: BlogEntry loadBlogEntry(Blog, String)
                  *
                  *  Preconditions:
                  *    blog != null
                  *    (soft) log != null
                  *
                  *  Postconditions:
                  *    return_value == One-of{&new BlogEntry(loadBlogEntry#2*), null}
                  *    return_value in Addr_Set{null,&new BlogEntry(loadBlogEntry#2*)}
                  *    new ArrayList(BlogEntry#2) num objects <= 1
                  *    new ArrayList(BlogEntry#3) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new ArrayList(Content#1) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new ArrayList(Content#3) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new BlogEntry(loadBlogEntry#2*) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new Date(PageBasedContent#2) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new HashSet(BlogEntry#1) num objects == new ArrayList(BlogEntry#2) num objects
                  *    new LinkedList(PageBasedContent#1) num objects == new ArrayList(BlogEntry#2) num objects
                  *    ...
                  */
        52      File path = new File(getPath(blog, blogEntryId, GMT));
        53      File file = new File(path, blogEntryId + ".xml");
        54      return loadBlogEntry(blog, file);
        55    }
        56
        57    /**
        58     * Loads a blog entry from the specified file.
        59     *
        60     * @param source    the File pointing to the source
        61     * @throws net.sourceforge.pebble.dao.PersistenceException
        62     *          if the blog entry can't be loaded
        63     */
        64    private BlogEntry loadBlogEntry(Blog blog, File source) throws PersistenceException {
                 /*
        P/P       *  Method: BlogEntry loadBlogEntry(Blog, File)
                  *
                  *  Preconditions:
                  *    source != null
                  *    (soft) log != null
                  *    (soft) blog != null
                  *
                  *  Presumptions:
                  *    javax.xml.parsers.SAXParserFactory:newInstance(...)@71 != null
                  *    javax.xml.parsers.SAXParserFactory:newSAXParser(...)@74 != null
                  *
                  *  Postconditions:
                  *    return_value in Addr_Set{null,&new BlogEntry(loadBlogEntry#2)}
                  *    new ArrayList(BlogEntry#2) num objects <= 1
                  *    new ArrayList(BlogEntry#3) num objects <= 1
                  *    new ArrayList(Content#1) num objects <= 1
                  *    new ArrayList(Content#3) num objects <= 1
                  *    new BlogEntry(loadBlogEntry#2) num objects <= 1
                  *    new BlogEntry(loadBlogEntry#2).author == &""
                  *    new BlogEntry(loadBlogEntry#2).blog == blog
                  *    new BlogEntry(loadBlogEntry#2).body == &""
                  *    (soft) new BlogEntry(loadBlogEntry#2).blog != null
                  *    ...
                  *
                  *  Test Vectors:
                  *    java.io.File:exists(...)@65: {0}, {1}
                  */
        65      if (source.exists()) {
        66        log.debug("Loading " + source.getAbsolutePath());
        67        BlogEntry blogEntry = new BlogEntry(blog);
        68
        69        try {
        70          DefaultHandler handler = new BlogEntryHandler(blogEntry);
        71          SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        72          saxFactory.setValidating(false);
        73          saxFactory.setNamespaceAware(true);
        74          SAXParser parser = saxFactory.newSAXParser();
        75          parser.parse(source, handler);
        76
        77        } catch (Exception e) {
        78          log.error(e.getMessage() + " while loading blog enty from " + source.getAbsolutePath(), e);
        79          e.printStackTrace();
        80          throw new PersistenceException(e.getMessage());
        81        }
        82
        83        return blogEntry;
        84      } else {
        85        return null;
        86      }
        87    }
        88
        89    /**
        90     * Loads all blog entries.
        91     *
        92     * @param blog the Blog to load all entries for
        93     * @return a List of BlogEntry objects
        94     * @throws net.sourceforge.pebble.dao.PersistenceException
        95     *          if the blog entries cannot be loaded
        96     */
        97    public Collection<BlogEntry> loadBlogEntries(Blog blog) throws PersistenceException {
                 /*
        P/P       *  Method: Collection loadBlogEntries(Blog)
                  *
                  *  Preconditions:
                  *    blog != null
                  *    (soft) log != null
                  *
                  *  Presumptions:
                  *    Local_13[Local_11]@103 != null
                  *    Local_18[Local_16]@105 != null
                  *    Local_23[Local_21]@107 != null
                  *    Local_8[Local_6]@101 != null
                  *    blogEntryFiles.length@107 <= 232-1
                  *    ...
                  *
                  *  Postconditions:
                  *    return_value == &new ArrayList(loadBlogEntries#1)
                  *    new ArrayList(loadBlogEntries#1) num objects == 1
                  */
        98      List<BlogEntry> list = new ArrayList<BlogEntry>();
        99
       100      File root = new File(blog.getRoot());
       101      File years[] = root.listFiles(new FourDigitFilenameFilter());
       102      for (File year : years) {
       103        File months[] = year.listFiles(new TwoDigitFilenameFilter());
       104        for (File month : months) {
       105          File days[] = month.listFiles(new TwoDigitFilenameFilter());
       106          for (File day : days) {
       107            File blogEntryFiles[] = day.listFiles(new BlogEntryFilenameFilter());
       108            for (File blogEntryFile : blogEntryFiles) {
       109              list.add(loadBlogEntry(blog, blogEntryFile));
       110            }
       111          }
       112        }
       113      }
       114
       115      return list;
       116    }
       117
       118    /**
       119     * Stores the specified blog entry.
       120     *
       121     * @param blogEntry the blog entry to store
       122     * @throws PersistenceException if something goes wrong storing the entry
       123     */
       124    public void storeBlogEntry(BlogEntry blogEntry) throws PersistenceException {
                 /*
        P/P       *  Method: void storeBlogEntry(BlogEntry)
                  *
                  *  Preconditions:
                  *    blogEntry != null
                  *    init'ed(blogEntry.attachment)
                  *    init'ed(blogEntry.categories)
                  *    blogEntry.comments != null
                  *    init'ed(blogEntry.commentsEnabled)
                  *    init'ed(blogEntry.excerpt)
                  *    init'ed(blogEntry.timeZoneId)
                  *    init'ed(blogEntry.trackBacks)
                  *    init'ed(blogEntry.trackBacksEnabled)
                  *    log != null
                  *    ...
                  *
                  *  Test Vectors:
                  *    java.io.File:exists(...)@126: {1}, {0}
                  */
       125      File outputDir = new File(getPath(blogEntry.getBlog(), blogEntry.getId(), GMT));
       126      if (!outputDir.exists()) {
       127        outputDir.mkdirs();
       128      }
       129
       130      File outputFile = new File(outputDir, blogEntry.getId() + ".xml");
       131      storeBlogEntry(blogEntry, outputFile);
       132    }
       133
       134
       135    /**
       136     * Stores a blog entry to the specified file.
       137     *
       138     * @param blogEntry   the BlogEntry that is being stored
       139     * @param destination the File pointing to the destination
       140     * @throws PersistenceException if something goes wrong storing the entry
       141     */
       142    private void storeBlogEntry(BlogEntry blogEntry, File destination) throws PersistenceException {
                 /*
        P/P       *  Method: void storeBlogEntry(BlogEntry, File)
                  *
                  *  Preconditions:
                  *    blogEntry != null
                  *    init'ed(blogEntry.attachment)
                  *    init'ed(blogEntry.categories)
                  *    blogEntry.comments != null
                  *    init'ed(blogEntry.commentsEnabled)
                  *    init'ed(blogEntry.excerpt)
                  *    init'ed(blogEntry.timeZoneId)
                  *    init'ed(blogEntry.trackBacks)
                  *    init'ed(blogEntry.trackBacksEnabled)
                  *    destination != null
                  *    ...
                  *
                  *  Presumptions:
                  *    comment.state@245 != null
                  *    java.io.StringWriter:getBuffer(...)@277 != null
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.author)
                  *    init'ed(blogEntry.body)
                  *
                  *  Presumptions:
                  *    java.util.Iterator:next(...)@205 != null
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.date)
                  *
                  *  Presumptions:
                  *    java.util.Iterator:next(...)@245 != null
                  *    java.util.Iterator:next(...)@252 != null
                  *    init'ed(java.util.Locale.ENGLISH)
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.originalPermalink)
                  *    blogEntry.state != null
                  *
                  *  Presumptions:
                  *    javax.xml.parsers.DocumentBuilder:newDocument(...)@152 != null
                  *    javax.xml.parsers.DocumentBuilderFactory:newDocumentBuilder(...)@151 != null
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.state.name)
                  *
                  *  Presumptions:
                  *    javax.xml.parsers.DocumentBuilderFactory:newInstance(...)@145 != null
                  *    javax.xml.transform.TransformerFactory:newInstance(...)@261 != null
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.subtitle)
                  *
                  *  Presumptions:
                  *    javax.xml.transform.TransformerFactory:newTransformer(...)@261 != null
                  *
                  *  Preconditions:
                  *    init'ed(blogEntry.tags)
                  *    init'ed(blogEntry.title)
                  *
                  *  Presumptions:
                  *    org.w3c.dom.Document:createElement(...)@154 != null
                  *    org.w3c.dom.Document:createElement(...)@157 != null
                  *    org.w3c.dom.Document:createElement(...)@158 != null
                  *    org.w3c.dom.Document:createElement(...)@159 != null
                  *    org.w3c.dom.Document:createElement(...)@160 != null
                  *    ...
                  *
                  *  Test Vectors:
                  *    blogEntry.attachment: Addr_Set{null}, Inverse{null}
                  *    blogEntry.excerpt: Addr_Set{null}, Inverse{null}
                  *    java.io.File:exists(...)@270: {0}, {1}
                  *    java.io.File:length(...)@270: {-263..0}, {1..264-1}
                  *    java.util.Iterator:hasNext(...)@204: {1}, {0}
                  *    java.util.Iterator:hasNext(...)@244: {1}, {0}
                  *    java.util.Iterator:hasNext(...)@251: {1}, {0}
                  *    blogEntry.author: Addr_Set{null}, Inverse{null}
                  *    blogEntry.originalPermalink: Addr_Set{null}, Inverse{null}
                  *    blogEntry.tags: Addr_Set{null}, Inverse{null}
                  */
       143      File backupFile = new File(destination.getParentFile(), destination.getName() + ".bak");
       144      try {
       145        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       146        factory.setValidating(false);
       147        factory.setNamespaceAware(true);
       148        factory.setIgnoringElementContentWhitespace(true);
       149        factory.setIgnoringComments(true);
       150
       151        DocumentBuilder builder = factory.newDocumentBuilder();
       152        Document doc = builder.newDocument();
       153
       154        Element root = doc.createElement("blogEntry");
       155        doc.appendChild(root);
       156
       157        Element titleNode = doc.createElement("title");
       158        Element subtitleNode = doc.createElement("subtitle");
       159        Element excerptNode = doc.createElement("excerpt");
       160        Element bodyNode = doc.createElement("body");
       161        Element categoryNode;
       162        Element tagsNode = doc.createElement("tags");
       163        Element dateNode = doc.createElement("date");
       164        Element timeZoneNode = doc.createElement("timeZone");
       165        Element stateNode = doc.createElement("state");
       166        Element authorNode = doc.createElement("author");
       167        Element staticNameNode = doc.createElement("staticName");
       168        Element commentsEnabledNode = doc.createElement("commentsEnabled");
       169        Element trackBacksEnabledNode = doc.createElement("trackBacksEnabled");
       170        Element attachmentNode = doc.createElement("attachment");
       171
       172        root.appendChild(titleNode);
       173        root.appendChild(subtitleNode);
       174        root.appendChild(excerptNode);
       175        root.appendChild(bodyNode);
       176        root.appendChild(dateNode);
       177        root.appendChild(timeZoneNode);
       178        root.appendChild(stateNode);
       179        root.appendChild(authorNode);
       180        root.appendChild(staticNameNode);
       181
       182        if (blogEntry.isAggregated()) {
       183          Element permalinkNode = doc.createElement("originalPermalink");
       184          permalinkNode.appendChild(doc.createTextNode(blogEntry.getOriginalPermalink()));
       185          root.appendChild(permalinkNode);
       186        }
       187
       188        titleNode.appendChild(doc.createTextNode(blogEntry.getTitle()));
       189        subtitleNode.appendChild(doc.createTextNode(blogEntry.getSubtitle()));
       190        bodyNode.appendChild(doc.createCDATASection(blogEntry.getBody()));
       191
       192        if (blogEntry.getExcerpt() != null) {
       193          excerptNode.appendChild(doc.createCDATASection(blogEntry.getExcerpt()));
       194        }
       195
       196        root.appendChild(commentsEnabledNode);
       197        commentsEnabledNode.appendChild(doc.createTextNode("" + blogEntry.isCommentsEnabled()));
       198
       199        root.appendChild(trackBacksEnabledNode);
       200        trackBacksEnabledNode.appendChild(doc.createTextNode("" + blogEntry.isTrackBacksEnabled()));
       201
       202        Iterator it = blogEntry.getCategories().iterator();
       203        Category category;
       204        while (it.hasNext()) {
       205          category = (Category) it.next();
       206          categoryNode = doc.createElement("category");
       207          categoryNode.appendChild(doc.createTextNode(category.getId()));
       208          root.appendChild(categoryNode);
       209        }
       210
       211        if (blogEntry.getTags() != null) {
       212          root.appendChild(tagsNode);
       213          tagsNode.appendChild(doc.createTextNode(blogEntry.getTags()));
       214        }
       215
       216        if (blogEntry.getAuthor() != null) {
       217          authorNode.appendChild(doc.createTextNode(blogEntry.getAuthor()));
       218        }
       219
       220        SimpleDateFormat sdf = new SimpleDateFormat(NEW_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);
       221        sdf.setTimeZone(GMT);
       222        dateNode.appendChild(doc.createTextNode(sdf.format(blogEntry.getDate())));
       223
       224        timeZoneNode.appendChild(doc.createTextNode(blogEntry.getTimeZoneId()));
       225
       226        stateNode.appendChild(createTextNode(doc, blogEntry.getState().getName()));
       227
       228        Attachment attachment = blogEntry.getAttachment();
       229        if (attachment != null) {
       230          root.appendChild(attachmentNode);
       231          Element attachmentUrlNode = doc.createElement("url");
       232          attachmentUrlNode.appendChild(createTextNode(doc, attachment.getUrl()));
       233          attachmentNode.appendChild(attachmentUrlNode);
       234          Element attachmentSizeNode = doc.createElement("size");
       235          attachmentSizeNode.appendChild(createTextNode(doc, "" + attachment.getSize()));
       236          attachmentNode.appendChild(attachmentSizeNode);
       237          Element attachmentTypeNode = doc.createElement("type");
       238          attachmentTypeNode.appendChild(createTextNode(doc, attachment.getType()));
       239          attachmentNode.appendChild(attachmentTypeNode);
       240        }
       241
       242        // and now store the comments
       243        it = blogEntry.getComments().iterator();
       244        while (it.hasNext()) {
       245          Comment comment = (Comment) it.next();
       246          storeComment(comment, doc, root);
       247        }
       248
       249        // and finally the trackbacks
       250        it = blogEntry.getTrackBacks().iterator();
       251        while (it.hasNext()) {
       252          TrackBack trackBack = (TrackBack) it.next();
       253          storeTrackBack(trackBack, doc, root);
       254        }
       255
       256        // write the XMl to a String, and then write this string to a file
       257        // (if the XML format fails, we don't corrupt the file)
       258        StringWriter sw = new StringWriter();
       259        Source source = new DOMSource(doc);
       260        Result result = new StreamResult(sw);
       261        Transformer xformer = TransformerFactory.newInstance().newTransformer();
       262        xformer.setOutputProperty(OutputKeys.METHOD, "xml");
       263        xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
       264        xformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
       265        xformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "body");
       266        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
       267        xformer.transform(source, result);
       268
       269        // now take a backup of the correct file
       270        if (destination.exists() && destination.length() > 0) {
       271          log.debug("Backing up to " + backupFile.getAbsolutePath());
       272          destination.renameTo(backupFile);
       273        }
       274
       275        log.debug("Saving to " + destination.getAbsolutePath());
       276        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destination), "UTF-8"));
       277        bw.write(sw.getBuffer().toString());
       278        bw.flush();
       279        bw.close();
       280      } catch (Exception e) {
       281        log.error(e.getMessage(), e);
       282        e.printStackTrace();
       283        throw new PersistenceException(e.getMessage());
       284      }
       285    }
       286
       287    /**
       288     * Helper method to store an individual comment.
       289     *
       290     * @param comment the Comment being stored
       291     * @param doc     the Document into which the comment is to be inserted
       292     * @param root    the root Node for the comment
       293     * @throws java.lang.Exception if something goes wrong
       294     */
       295    private void storeComment(Comment comment, Document doc, Node root) throws Exception {
                 /*
        P/P       *  Method: void storeComment(Comment, Document, Node)
                  *
                  *  Preconditions:
                  *    comment != null
                  *    init'ed(comment.authenticated)
                  *    init'ed(comment.author)
                  *    init'ed(comment.body)
                  *    init'ed(comment.date)
                  *    init'ed(comment.email)
                  *    init'ed(comment.ipAddress)
                  *    init'ed(comment.parent)
                  *    comment.state != null
                  *    init'ed(comment.state.name)
                  *    ...
                  *
                  *  Presumptions:
                  *    init'ed(java.util.Locale.ENGLISH)
                  *    org.w3c.dom.Document:createElement(...)@296 != null
                  *    org.w3c.dom.Document:createElement(...)@299 != null
                  *    org.w3c.dom.Document:createElement(...)@300 != null
                  *    org.w3c.dom.Document:createElement(...)@301 != null
                  *    ...
                  *
                  *  Test Vectors:
                  *    comment.parent: Addr_Set{null}, Inverse{null}
                  */
       296      Element commentNode = doc.createElement("comment");
       297      root.appendChild(commentNode);
       298
       299      Element titleNode = doc.createElement("title");
       300      Element bodyNode = doc.createElement("body");
       301      Element authorNode = doc.createElement("author");
       302      Element emailNode = doc.createElement("email");
       303      Element websiteNode = doc.createElement("website");
       304      Element ipAddressNode = doc.createElement("ipAddress");
       305      Element dateNode = doc.createElement("date");
       306      Element parentNode = doc.createElement("parent");
       307      Element stateNode = doc.createElement("state");
       308      Element authenticatedNode = doc.createElement("authenticated");
       309
       310      commentNode.appendChild(titleNode);
       311      commentNode.appendChild(bodyNode);
       312      commentNode.appendChild(authorNode);
       313      commentNode.appendChild(emailNode);
       314      commentNode.appendChild(websiteNode);
       315      commentNode.appendChild(ipAddressNode);
       316      commentNode.appendChild(dateNode);
       317      commentNode.appendChild(stateNode);
       318      commentNode.appendChild(authenticatedNode);
       319
       320      titleNode.appendChild(createTextNode(doc, comment.getTitle()));
       321      bodyNode.appendChild(createCDATASection(doc, comment.getBody()));
       322      authorNode.appendChild(createTextNode(doc, comment.getAuthor()));
       323      emailNode.appendChild(createTextNode(doc, comment.getEmail()));
       324      websiteNode.appendChild(createTextNode(doc, comment.getWebsite()));
       325      ipAddressNode.appendChild(createTextNode(doc, comment.getIpAddress()));
       326      SimpleDateFormat sdf = new SimpleDateFormat(NEW_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);
       327      sdf.setTimeZone(GMT);
       328      dateNode.appendChild(createTextNode(doc, sdf.format(comment.getDate())));
       329      stateNode.appendChild(createTextNode(doc, comment.getState().getName()));
       330      authenticatedNode.appendChild(createTextNode(doc, "" + comment.isAuthenticated()));
       331
       332      if (comment.getParent() != null) {
       333        commentNode.appendChild(parentNode);
       334        parentNode.appendChild(createTextNode(doc, "" + comment.getParent().getId()));
       335      }
       336    }
       337
       338    private Node createCDATASection(Document doc, String text) {
                 /*
        P/P       *  Method: Node createCDATASection(Document, String)
                  *
                  *  Preconditions:
                  *    doc != null
                  *
                  *  Postconditions:
                  *    init'ed(return_value)
                  *
                  *  Test Vectors:
                  *    text: Addr_Set{null}, Inverse{null}
                  */
       339      if (text != null) {
       340        return doc.createCDATASection(text);
       341      } else {
       342        return doc.createCDATASection("");
       343      }
       344    }
       345
       346    private Node createTextNode(Document doc, String text) {
                 /*
        P/P       *  Method: Node createTextNode(Document, String)
                  *
                  *  Preconditions:
                  *    doc != null
                  *
                  *  Postconditions:
                  *    init'ed(return_value)
                  *
                  *  Test Vectors:
                  *    text: Addr_Set{null}, Inverse{null}
                  */
       347      if (text != null) {
       348        return doc.createTextNode(text);
       349      } else {
       350        return doc.createTextNode("");
       351      }
       352    }
       353
       354    /**
       355     * Helper method to store an individual trackback.
       356     *
       357     * @param trackBack the TrackBack being stored
       358     * @param doc       the Document into which the trackback is to be inserted
       359     * @param root      the root Node for the comment
       360     * @throws java.lang.Exception if something goes wrong
       361     */
       362    private void storeTrackBack(TrackBack trackBack, Document doc, Node root) throws Exception {
                 /*
        P/P       *  Method: void storeTrackBack(TrackBack, Document, Node)
                  *
                  *  Preconditions:
                  *    doc != null
                  *    root != null
                  *    trackBack != null
                  *    init'ed(trackBack.blogName)
                  *    init'ed(trackBack.date)
                  *    init'ed(trackBack.excerpt)
                  *    init'ed(trackBack.ipAddress)
                  *    trackBack.state != null
                  *    init'ed(trackBack.state.name)
                  *    init'ed(trackBack.title)
                  *    ...
                  *
                  *  Presumptions:
                  *    init'ed(java.util.Locale.ENGLISH)
                  *    org.w3c.dom.Document:createElement(...)@363 != null
                  *    org.w3c.dom.Document:createElement(...)@366 != null
                  *    org.w3c.dom.Document:createElement(...)@367 != null
                  *    org.w3c.dom.Document:createElement(...)@368 != null
                  *    ...
                  */
       363      Element commentNode = doc.createElement("trackback");
       364      root.appendChild(commentNode);
       365
       366      Element titleNode = doc.createElement("title");
       367      Element excerptNode = doc.createElement("excerpt");
       368      Element urlNode = doc.createElement("url");
       369      Element blogNameNode = doc.createElement("blogName");
       370      Element ipAddressNode = doc.createElement("ipAddress");
       371      Element dateNode = doc.createElement("date");
       372      Element stateNode = doc.createElement("state");
       373
       374      commentNode.appendChild(titleNode);
       375      commentNode.appendChild(excerptNode);
       376      commentNode.appendChild(urlNode);
       377      commentNode.appendChild(blogNameNode);
       378      commentNode.appendChild(ipAddressNode);
       379      commentNode.appendChild(dateNode);
       380      commentNode.appendChild(stateNode);
       381
       382      titleNode.appendChild(createTextNode(doc, trackBack.getTitle()));
       383      excerptNode.appendChild(createCDATASection(doc, trackBack.getExcerpt()));
       384      urlNode.appendChild(createTextNode(doc, trackBack.getUrl()));
       385      blogNameNode.appendChild(createTextNode(doc, trackBack.getBlogName()));
       386      ipAddressNode.appendChild(createTextNode(doc, trackBack.getIpAddress()));
       387      SimpleDateFormat sdf = new SimpleDateFormat(NEW_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);
       388      sdf.setTimeZone(GMT);
       389      dateNode.appendChild(doc.createTextNode(sdf.format(trackBack.getDate())));
       390      stateNode.appendChild(createTextNode(doc, trackBack.getState().getName()));
       391    }
       392
       393    /**
       394     * Removes the specified blog entry.
       395     *
       396     * @param blogEntry the blog entry to remove
       397     * @throws PersistenceException if something goes wrong removing the entry
       398     */
       399    public void removeBlogEntry(BlogEntry blogEntry) throws PersistenceException {
                 /*
        P/P       *  Method: void removeBlogEntry(BlogEntry)
                  *
                  *  Preconditions:
                  *    blogEntry != null
                  *    init'ed(blogEntry.blog.id)
                  *    blogEntry.blog != null
                  *    init'ed(blogEntry.id)
                  *    log != null
                  *
                  *  Presumptions:
                  *    java.io.File:delete(...)@404 == 1
                  */
       400      File path = new File(getPath(blogEntry.getBlog(), blogEntry.getId(), GMT));
       401      File file = new File(path, blogEntry.getId() + ".xml");
       402      log.debug("Removing " + blogEntry.getGuid());
       403
       404      boolean success = file.delete();
       405      if (!success) {
       406        throw new PersistenceException("Deletion of blog entry " + blogEntry.getGuid() + " failed");
       407      }
       408    }
       409
       410    /**
       411     * Given a blog and blog entry ID, this method determines the path where
       412     * that blog entry is stored.
       413     *
       414     * @param blog    the owning Blog
       415     * @param blogEntryId   the ID of the blog entry
       416     * @return  a String of the form blogroot/yyyy/MM/dd
       417     */
       418    public String getPath(Blog blog, String blogEntryId, TimeZone timeZone) {
                 /*
        P/P       *  Method: String getPath(Blog, String, TimeZone)
                  *
                  *  Preconditions:
                  *    blog != null
                  *
                  *  Presumptions:
                  *    init'ed(java.io.File.separator)
                  *
                  *  Postconditions:
                  *    return_value != null
                  */
       419      DateFormat year = new SimpleDateFormat("yyyy");
       420      year.setTimeZone(timeZone);
       421      DateFormat month = new SimpleDateFormat("MM");
       422      month.setTimeZone(timeZone);
       423      DateFormat day = new SimpleDateFormat("dd");
       424      day.setTimeZone(timeZone);
       425
       426      long dateInMillis = Long.parseLong(blogEntryId);
       427      Date date = new Date(dateInMillis);
       428
       429      StringBuffer buf = new StringBuffer();
       430      buf.append(blog.getRoot());
       431      buf.append(File.separator);
       432      buf.append(year.format(date));
       433      buf.append(File.separator);
       434      buf.append(month.format(date));
       435      buf.append(File.separator);
       436      buf.append(day.format(date));
       437
       438      return buf.toString();
       439    }
       440
       441  }

SofCheck Inspector Build Version : 2.22510

fileblogentrydao.java | 2010-Jun-25 19:40:32
fileblogentrydao.class | 2010-Jul-19 20:23:40