File Source: filestaticpagedao.java

         /* 
    P/P   *  Method: void net.sourceforge.pebble.dao.file.FileStaticPageDAO$1(FileStaticPageDAO)
          */
     1  package net.sourceforge.pebble.dao.file;
     2  
     3  import net.sourceforge.pebble.dao.PersistenceException;
     4  import net.sourceforge.pebble.dao.StaticPageDAO;
     5  import net.sourceforge.pebble.domain.Blog;
     6  import net.sourceforge.pebble.domain.StaticPage;
     7  import net.sourceforge.pebble.util.SecurityUtils;
     8  import org.apache.commons.logging.Log;
     9  import org.apache.commons.logging.LogFactory;
    10  
         /* 
    P/P   *  Method: void net.sourceforge.pebble.dao.file.FileStaticPageDAO()
          * 
          *  Presumptions:
          *    java.lang.Class:getPackage(...)@36 != null
          *    java.lang.Object:getClass(...)@36 != null
          * 
          *  Postconditions:
          *    possibly_updated(this.jaxbContext)
          */
    11  import javax.xml.bind.JAXBContext;
    12  import javax.xml.bind.JAXBElement;
    13  import javax.xml.bind.Marshaller;
    14  import javax.xml.bind.Unmarshaller;
    15  import java.io.*;
    16  import java.text.SimpleDateFormat;
    17  import java.text.DateFormat;
    18  import java.text.ParseException;
    19  import java.util.*;
    20  
    21  public class FileStaticPageDAO implements StaticPageDAO {
    22  
    23    /**
    24     * the log used by this class
    25     */
           /* 
    P/P     *  Method: Log access$0()
            * 
            *  Preconditions:
            *    init'ed(log)
            * 
            *  Postconditions:
            *    return_value == log
            *    init'ed(return_value)
            */
    26    private static Log log = LogFactory.getLog(FileStaticPageDAO.class);
    27  
    28    private static final String STATIC_PAGES_DIRECTORY_NAME = "pages";
    29    private static final String STATIC_PAGE_FILE_EXTENSION = ".xml";
    30    private static final String STATIC_PAGE_LOCK_EXTENSION = ".lock";
    31  
    32    private JAXBContext jaxbContext;
    33  
    34    public FileStaticPageDAO() {
    35      try {
    36        jaxbContext = JAXBContext.newInstance(getClass().getPackage().getName());
    37      } catch (Exception e) {
    38        e.printStackTrace();
    39      }
    40    }
    41  
    42    /** the date/time format used when persisting dates */
    43    static final String OLD_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss z";
    44    static final String NEW_PERSISTENT_DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss:S Z";
    45    static final String REGEX_FOR_YEAR = "\\d\\d\\d\\d";
    46  
    47    /**
    48     * Loads the static pages for a given blog.
    49     *
    50     * @param blog the owning Blog instance
    51     * @return a Collection of StaticPage instances
    52     * @throws net.sourceforge.pebble.dao.PersistenceException
    53     *          if static pages cannot be loaded
    54     */
           /* 
    P/P     *  Method: Collection loadStaticPages(Blog)
            * 
            *  Preconditions:
            *    blog != null
            * 
            *  Presumptions:
            *    Local_8[Local_6]@58 != null
            *    files.length@58 <= 232-1
            * 
            *  Postconditions:
            *    return_value == &new ArrayList(loadStaticPages#1)
            *    new ArrayList(loadStaticPages#1) num objects == 1
            * 
            *  Test Vectors:
            *    java.io.File:listFiles(...)@58: Addr_Set{null}, Inverse{null}
            *    loadStaticPage(...)@88: Addr_Set{null}, Inverse{null}
            */
    55    public Collection<StaticPage> loadStaticPages(Blog blog) throws PersistenceException {
    56      List<StaticPage> list = new ArrayList<StaticPage>();
    57      File root = new File(blog.getRoot(), STATIC_PAGES_DIRECTORY_NAME);
    58      File files[] = root.listFiles(new FilenameFilter() {
    59          public boolean accept(File dir, String name) {
                   /* 
    P/P             *  Method: bool accept(File, String)
                    * 
                    *  Preconditions:
                    *    (soft) name != null
                    * 
                    *  Postconditions:
                    *    init'ed(return_value)
                    * 
                    *  Test Vectors:
                    *    java.io.File:isDirectory(...)@60: {0}, {1}
                    *    java.lang.String:matches(...)@60: {0}, {1}
                    */
    60            return new File(dir, name).isDirectory() && name.matches("\\d+");
    61          }
    62      });
    63      
    64      if (files != null) {
    65        for (File file : files) {
    66          StaticPage staticPage = loadStaticPage(blog, file.getName());
    67          if (staticPage != null) {
    68            list.add(staticPage);
    69          }
    70        }
    71      }
    72  
    73      return list;
    74    }
    75  
    76    /**
    77     * Loads a specific static page.
    78     *
    79     * @param blog   the owning Blog
    80     * @param pageId the page ID
    81     * @return a StaticPage instance
    82     * @throws net.sourceforge.pebble.dao.PersistenceException
    83     *          if the static page cannot be loaded
    84     */
           /* 
    P/P     *  Method: StaticPage loadStaticPage(Blog, String)
            * 
            *  Preconditions:
            *    blog != null
            * 
            *  Postconditions:
            *    init'ed(return_value)
            */
    85    public StaticPage loadStaticPage(Blog blog, String pageId) throws PersistenceException {
    86      File path = new File(getPath(blog, pageId));
    87      File file = new File(path, pageId + STATIC_PAGE_FILE_EXTENSION);
    88      return loadStaticPage(blog, file);
    89    }
    90  
    91    /**
    92     * Loads a static page from the specified file.
    93     *
    94     * @param blog      the Blog to which the static page belongs
    95     * @param source    the File pointing to the source
    96     * @return    a StaticPage instance
    97     * @throws net.sourceforge.pebble.dao.PersistenceException
    98     *          if the static page can't be loaded
    99     */
   100    private StaticPage loadStaticPage(Blog blog, File source) throws PersistenceException {
   101      if (source.exists()) {
   102        log.debug("Loading static page from " + source.getAbsolutePath());
   103        StaticPage staticPage = new StaticPage(blog);
   104  
   105        try {
   106          Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
   107          JAXBElement<StaticPageType> controller = (JAXBElement)unmarshaller.unmarshal(source);
   108          StaticPageType spt = controller.getValue();
   109  
   110          staticPage.setTitle(spt.getTitle());
   111          staticPage.setSubtitle(spt.getSubtitle());
   112          staticPage.setBody(spt.getBody());
   113          staticPage.setTags(spt.getTags());
   114          staticPage.setAuthor(spt.getAuthor());
   115          staticPage.setOriginalPermalink(spt.getOriginalPermalink());
   116          staticPage.setName(spt.getStaticName());
   117          StaticPageDateConverter converter = new StaticPageDateConverter(staticPage);
   118          staticPage.setDate(converter.parse(spt.getDate()));
   119          staticPage.setTemplate(spt.getTemplate());
   120  
   121        } catch (Exception e) {
   122          log.error(e.getMessage(), e);
   123          e.printStackTrace();
   124          throw new PersistenceException(e.getMessage());
   125        }
   126  
   127        // and is the page locked?
   128        staticPage.setLockedBy(getUsernameHoldingLock(staticPage));
   129  
   130        return staticPage;
   131      } else {
   132        return null;
   133      }
   134    }
   135  
   136    /**
   137     * Stores the specified static page.
   138     *
   139     * @param staticPage the static page to store
   140     * @throws net.sourceforge.pebble.dao.PersistenceException
   141     *          if something goes wrong storing the static page
   142     */
           /* 
    P/P     *  Method: void storeStaticPage(StaticPage)
            * 
            *  Preconditions:
            *    staticPage != null
            *    staticPage.blog != null
            *    init'ed(staticPage.id)
            * 
            *  Test Vectors:
            *    java.io.File:exists(...)@145: {1}, {0}
            */
   143    public void storeStaticPage(StaticPage staticPage) throws PersistenceException {
   144      File outputDir = new File(getPath(staticPage.getBlog(), staticPage.getId()));
   145      if (!outputDir.exists()) {
   146        outputDir.mkdirs();
   147      }
   148  
   149      File outputFile = new File(outputDir, staticPage.getId() + STATIC_PAGE_FILE_EXTENSION);
   150      storeStaticPage(staticPage, outputFile);
   151    }
   152  
   153    /**
   154     * Stores a static page to the specified file.
   155     *
   156     * @param staticPage    the StaticPage that is being stored
   157     * @param destination the File pointing to the destination
   158     * @throws PersistenceException if something goes wrong storing the static page
   159     */
   160    private void storeStaticPage(StaticPage staticPage, File destination) throws PersistenceException {
   161      try {
   162        Marshaller marshaller = jaxbContext.createMarshaller();
   163        StaticPageType type = new StaticPageType();
   164  
   165        type.setTitle(staticPage.getTitle());
   166        type.setSubtitle(staticPage.getSubtitle());
   167        type.setBody(staticPage.getBody());
   168        type.setTags(staticPage.getTags());
   169        type.setAuthor(staticPage.getAuthor());
   170        type.setStaticName(staticPage.getName());
   171        type.setOriginalPermalink(staticPage.getOriginalPermalink());
   172        type.setState(ContentState.PUBLISHED);
   173        type.setTitle(staticPage.getTitle());
   174        type.setTemplate(staticPage.getTemplate());
   175  
   176        StaticPageDateConverter converter = new StaticPageDateConverter(staticPage);
   177        type.setDate(converter.format(staticPage.getDate()));
   178  
   179        // now take a backup of the correct file
   180        if (destination.exists() && destination.length() > 0) {
   181          removeStaticPage(staticPage); // this archives the current version
   182        }
   183  
   184        log.debug("Saving to " + destination.getAbsolutePath());
   185        ObjectFactory objectFactory = new ObjectFactory();
   186        JAXBElement jaxbElement = objectFactory.createStaticPage(type);
   187  
   188        marshaller.setProperty("jaxb.formatted.output", true);
   189        marshaller.setProperty("jaxb.encoding", staticPage.getBlog().getCharacterEncoding());
   190        FileWriter writer = new FileWriter(destination);
   191        marshaller.marshal(jaxbElement, writer);
   192        writer.flush();
   193        writer.close();
   194      } catch (Exception e) {
   195        log.error(e.getMessage(), e);
   196        e.printStackTrace();
   197        throw new PersistenceException(e.getMessage());
   198      }
   199    }
   200  
   201    /**
   202     * Removes the specified static page.
   203     *
   204     * @param staticPage the static page to remove
   205     * @throws net.sourceforge.pebble.dao.PersistenceException
   206     *          if something goes wrong removing the page
   207     */
           /* 
    P/P     *  Method: void removeStaticPage(StaticPage)
            * 
            *  Preconditions:
            *    log != null
            *    staticPage != null
            *    staticPage.blog != null
            *    init'ed(staticPage.blog.id)
            *    init'ed(staticPage.id)
            * 
            *  Presumptions:
            *    java.io.File:renameTo(...)@230 == 1
            * 
            *  Test Vectors:
            *    java.io.File:exists(...)@218: {0}, {1}
            *    java.io.File:exists(...)@225: {0}, {1}
            */
   208    public void removeStaticPage(StaticPage staticPage) throws PersistenceException {
   209      File path = new File(getPath(staticPage.getBlog(), staticPage.getId()));
   210      File file = new File(path, staticPage.getId() + STATIC_PAGE_FILE_EXTENSION);
   211      log.debug("Removing " + staticPage.getGuid());
   212  
   213      // for archive purposes, the current version of the file will be saved with
   214      // the timestamp as the extension
   215      SimpleDateFormat archiveFileExtension = new SimpleDateFormat("yyyyMMdd-HHmmss");
   216      archiveFileExtension.setTimeZone(staticPage.getBlog().getTimeZone());
   217      Date date = new Date();
   218      if (file.exists()) {
   219        date = new Date(file.lastModified());
   220      }
   221      File backupFile = new File(
   222          file.getParentFile(),
   223          file.getName() + "." + archiveFileExtension.format(date));
   224  
   225      if (backupFile.exists()) {
   226        backupFile.delete();
   227      }
   228  
   229      log.debug("Archiving current version to " + backupFile.getAbsolutePath());
   230      boolean success = file.renameTo(backupFile);
   231  
   232      if (!success) {
   233        throw new PersistenceException("Deletion of " + staticPage.getGuid() + " failed");
   234      }
   235    }
   236  
   237    /**
   238     * Given a blog and static page ID, this method determines the path where
   239     * that static page is stored.
   240     *
   241     * @param blog    the owning Blog
   242     * @param staticPageId   the ID of the static page
   243     * @return  a String of the form blogroot/yyyy/MM/dd
   244     */
           /* 
    P/P     *  Method: String getPath(Blog, String)
            * 
            *  Preconditions:
            *    blog != null
            * 
            *  Presumptions:
            *    init'ed(java.io.File.separator)
            * 
            *  Postconditions:
            *    return_value != null
            */
   245    private String getPath(Blog blog, String staticPageId) {
   246      StringBuffer buf = new StringBuffer();
   247      buf.append(blog.getRoot());
   248      buf.append(File.separator);
   249      buf.append("pages");
   250      buf.append(File.separator);
   251      buf.append(staticPageId);
   252  
   253      return buf.toString();
   254    }
   255  
   256    /**
   257     * Locks the specified static page.
   258     *
   259     * @param staticPage the static page to lock
   260     * @return  true if the page could be locked, false otherwise
   261     */
           /* 
    P/P     *  Method: bool lock(StaticPage)
            * 
            *  Preconditions:
            *    staticPage.blog != null
            *    init'ed(staticPage.id)
            *    (soft) log != null
            *    (soft) staticPage != null
            *    (soft) init'ed(staticPage.blog.id)
            * 
            *  Postconditions:
            *    init'ed(return_value)
            * 
            *  Test Vectors:
            *    java.io.File:createNewFile(...)@265: {0}, {1}
            *    java.lang.String:equals(...)@274: {0}, {1}
            */
   262    public boolean lock(StaticPage staticPage) {
   263      File lockFile = getLockFile(staticPage);
   264      try {
   265        boolean success = lockFile.createNewFile();
   266        if (success) {
   267          FileWriter writer = new FileWriter(lockFile);
   268          writer.write(SecurityUtils.getUsername());
   269          writer.flush();
   270          writer.close();
   271          return true;
   272        } else {
   273          String lockedBy = getUsernameHoldingLock(staticPage);
   274          return (lockedBy != null && lockedBy.equals(SecurityUtils.getUsername()));
   275        }
   276      } catch (IOException e) {
   277        log.warn("Exceptoin while attempting to lock static page " + staticPage.getGuid(), e);
   278      }
   279  
   280      return false;
   281    }
   282  
   283    /**
   284     * Unlocks the specified static page.
   285     *
   286     * @param staticPage the static page to unlock
   287     * @return true if the page could be unlocked, false otherwise
   288     */
           /* 
    P/P     *  Method: bool unlock(StaticPage)
            * 
            *  Preconditions:
            *    staticPage != null
            *    staticPage.blog != null
            *    init'ed(staticPage.id)
            * 
            *  Postconditions:
            *    init'ed(return_value)
            * 
            *  Test Vectors:
            *    java.io.File:exists(...)@291: {0}, {1}
            */
   289    public boolean unlock(StaticPage staticPage) {
   290      File lockFile = getLockFile(staticPage);
   291      if (lockFile.exists()) {
   292        return lockFile.delete();
   293      } else {
   294        return true;
   295      }
   296    }
   297  
   298    /**
   299     * Given a static page, this method determines the path where
   300     * that static page is stored.
   301     *
   302     * @param staticPage    a StaticPage instance
   303     * @return  a File instance, representing a lock
   304     */
           /* 
    P/P     *  Method: File getLockFile(StaticPage)
            * 
            *  Preconditions:
            *    staticPage != null
            *    staticPage.blog != null
            *    init'ed(staticPage.id)
            * 
            *  Presumptions:
            *    init'ed(java.io.File.separator)
            * 
            *  Postconditions:
            *    return_value == &new File(getLockFile#2)
            *    new File(getLockFile#2) num objects == 1
            */
   305    private File getLockFile(StaticPage staticPage) {
   306      StringBuffer buf = new StringBuffer();
   307      buf.append(staticPage.getBlog().getRoot());
   308      buf.append(File.separator);
   309      buf.append(STATIC_PAGES_DIRECTORY_NAME);
   310      buf.append(File.separator);
   311      buf.append(staticPage.getId());
   312      buf.append(STATIC_PAGE_LOCK_EXTENSION);
   313  
   314      return new File(buf.toString());
   315    }
   316  
           /* 
    P/P     *  Method: String getUsernameHoldingLock(StaticPage)
            * 
            *  Preconditions:
            *    (soft) log != null
            *    (soft) staticPage != null
            *    (soft) staticPage.blog != null
            *    (soft) init'ed(staticPage.id)
            * 
            *  Postconditions:
            *    init'ed(return_value)
            * 
            *  Test Vectors:
            *    java.io.File:exists(...)@321: {0}, {1}
            */
   317    private String getUsernameHoldingLock(StaticPage staticPage) {
   318      String username = null;
   319      try {
   320        File lockFile = getLockFile(staticPage);
   321        if (lockFile.exists()) {
   322          BufferedReader reader = new BufferedReader(new FileReader(lockFile));
   323          username = reader.readLine();
   324          reader.close();
   325        }
   326      } catch (IOException ioe) {
   327        log.warn("Error reading lock file", ioe);
   328      }
   329  
   330      return username;
   331    }
   332  
   333    class StaticPageDateConverter {
   334  
   335      private SimpleDateFormat dateTimeFormats[];
   336  
   337      StaticPageDateConverter(StaticPage staticPage) {
   338        // create all date/time formats, for backwards compatibility
   339        SimpleDateFormat format;
   340        dateTimeFormats = new SimpleDateFormat[6];
   341  
   342        format = new SimpleDateFormat(FileBlogEntryDAO.NEW_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);
   343        format.setTimeZone(staticPage.getBlog().getTimeZone());
   344        dateTimeFormats[0] = format;
   345  
   346        format = new SimpleDateFormat(FileBlogEntryDAO.NEW_PERSISTENT_DATETIME_FORMAT, staticPage.getBlog().getLocale());
   347        format.setTimeZone(staticPage.getBlog().getTimeZone());
   348        dateTimeFormats[1] = format;
   349  
   350        format = new SimpleDateFormat(FileBlogEntryDAO.NEW_PERSISTENT_DATETIME_FORMAT);
   351        format.setTimeZone(staticPage.getBlog().getTimeZone());
   352        dateTimeFormats[2] = format;
   353  
   354        format = new SimpleDateFormat(FileBlogEntryDAO.OLD_PERSISTENT_DATETIME_FORMAT, Locale.ENGLISH);
   355        format.setTimeZone(staticPage.getBlog().getTimeZone());
   356        dateTimeFormats[3] = format;
   357  
   358        format = new SimpleDateFormat(FileBlogEntryDAO.OLD_PERSISTENT_DATETIME_FORMAT, staticPage.getBlog().getLocale());
   359        format.setTimeZone(staticPage.getBlog().getTimeZone());
   360        dateTimeFormats[4] = format;
   361  
   362        format = new SimpleDateFormat(FileBlogEntryDAO.OLD_PERSISTENT_DATETIME_FORMAT);
   363        format.setTimeZone(staticPage.getBlog().getTimeZone());
   364        dateTimeFormats[5] = format;
   365      }
   366  
             /* 
    P/P       *  Method: Date parse(String)
              * 
              *  Preconditions:
              *    this.dateTimeFormats != null
              *    this.dateTimeFormats.length <= 232-1
              *    (soft) net/sourceforge/pebble/dao/file/FileStaticPageDAO.log != null
              *    (soft) this.dateTimeFormats[...] != null
              * 
              *  Postconditions:
              *    init'ed(return_value)
              */
   367      Date parse(String s) {
   368        for (DateFormat dateTimeFormat : dateTimeFormats) {
   369          try {
   370            return dateTimeFormat.parse(s);
   371          } catch (ParseException pe) {
   372            // do nothing, just try the next one
   373          }
   374        }
   375  
   376        log.error("Could not parse date of " + s);
   377        return null;
   378      }
   379  
             /* 
    P/P       *  Method: String format(Date)
              * 
              *  Preconditions:
              *    this.dateTimeFormats != null
              *    this.dateTimeFormats.length >= 1
              *    this.dateTimeFormats[0] != null
              * 
              *  Postconditions:
              *    init'ed(return_value)
              */
   380      String format(Date date) {
   381        return dateTimeFormats[0].format(date);
   382      }
   383  
   384    }
   385  
   386  }








SofCheck Inspector Build Version : 2.22510
filestaticpagedao.java 2010-Jun-25 19:40:32
filestaticpagedao.class 2010-Jul-19 20:23:40
filestaticpagedao$1.class 2010-Jul-19 20:23:40
filestaticpagedao$staticpagedateconverter.class 2010-Jul-19 20:23:40