File Source: uploadfileaction.java

         /* 
    P/P   *  Method: net.sourceforge.pebble.web.action.UploadFileAction__static_init
          * 
          *  Postconditions:
          *    init'ed(log)
          */
     1  /*
     2   * Copyright (c) 2003-2006, Simon Brown
     3   * All rights reserved.
     4   *
     5   * Redistribution and use in source and binary forms, with or without
     6   * modification, are permitted provided that the following conditions are met:
     7   *
     8   *   - Redistributions of source code must retain the above copyright
     9   *     notice, this list of conditions and the following disclaimer.
    10   *
    11   *   - Redistributions in binary form must reproduce the above copyright
    12   *     notice, this list of conditions and the following disclaimer in
    13   *     the documentation and/or other materials provided with the
    14   *     distribution.
    15   *
    16   *   - Neither the name of Pebble nor the names of its contributors may
    17   *     be used to endorse or promote products derived from this software
    18   *     without specific prior written permission.
    19   *
    20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    30   * POSSIBILITY OF SUCH DAMAGE.
    31   */
    32  package net.sourceforge.pebble.web.action;
    33  
    34  import net.sourceforge.pebble.Constants;
    35  import net.sourceforge.pebble.PebbleContext;
    36  import net.sourceforge.pebble.domain.FileManager;
    37  import net.sourceforge.pebble.domain.FileMetaData;
    38  import net.sourceforge.pebble.domain.Blog;
    39  import net.sourceforge.pebble.domain.BlogManager;
    40  import net.sourceforge.pebble.web.view.RedirectView;
    41  import net.sourceforge.pebble.web.view.View;
    42  import net.sourceforge.pebble.web.view.impl.FileTooLargeView;
    43  import net.sourceforge.pebble.web.view.impl.NotEnoughSpaceView;
         /* 
    P/P   *  Method: void net.sourceforge.pebble.web.action.UploadFileAction()
          */
    44  import org.apache.commons.fileupload.DiskFileUpload;
    45  import org.apache.commons.fileupload.FileItem;
    46  import org.apache.commons.fileupload.FileUpload;
    47  import org.apache.commons.fileupload.FileUploadBase;
    48  import org.apache.commons.logging.Log;
    49  import org.apache.commons.logging.LogFactory;
    50  
    51  import javax.servlet.ServletException;
    52  import javax.servlet.http.HttpServletRequest;
    53  import javax.servlet.http.HttpServletResponse;
    54  import java.io.File;
    55  import java.util.Iterator;
    56  import java.util.List;
    57  
    58  /**
    59   * Superclass for actions that allow the user to upload a file.
    60   *
    61   * @author    Simon Brown
    62   */
    63  public abstract class UploadFileAction extends AbstractFileAction {
    64  
    65    private static final Log log = LogFactory.getLog(UploadFileAction.class);
    66  
    67    /**
    68     * Peforms the processing associated with this action.
    69     *
    70     * @param request  the HttpServletRequest instance
    71     * @param response the HttpServletResponse instance
    72     * @return the name of the next view
    73     */
    74    public View process(HttpServletRequest request, HttpServletResponse response) throws ServletException {
             /* 
    P/P       *  Method: View process(HttpServletRequest, HttpServletResponse)
              * 
              *  Preconditions:
              *    this.model != null
              *    this.model.data != null
              *    (soft) net.sourceforge.pebble.PebbleContext__static_init.new PebbleContext(PebbleContext__static_init#1).configuration != null
              *    (soft) response != null
              * 
              *  Presumptions:
              *    java.lang.Integer:parseInt(...)@105 in 0..9
              *    java.lang.Integer:parseInt(...)@119 in 0..9
              *    java.util.HashMap:get(...)@63 != null
              *    java.util.Iterator:next(...)@103 != null
              *    java.util.Iterator:next(...)@116 != null
              *    ...
              * 
              *  Postconditions:
              *    return_value in Addr_Set{null,&new NotEnoughSpaceView(process#10),&new FileTooLargeView(process#4),&new RedirectView(process#12)}
              *    new FileTooLargeView(process#4) num objects <= 1
              *    new NotEnoughSpaceView(process#10) num objects <= 1
              *    new RedirectView(process#12) num objects <= 1
              * 
              *  Test Vectors:
              *    java.lang.String:equals(...)@108: {0}, {1}
              *    java.lang.String:equals(...)@140: {0}, {1}
              *    java.lang.String:length(...)@123: {1..232-1}, {0}
              *    java.lang.String:startsWith(...)@104: {0}, {1}
              *    java.lang.String:startsWith(...)@118: {0}, {1}
              *    java.util.Iterator:hasNext(...)@102: {1}, {0}
              *    java.util.Iterator:hasNext(...)@115: {1}, {0}
              *    net.sourceforge.pebble.domain.FileManager:hasEnoughSpace(...)@135: {0}, {1}
              *    net.sourceforge.pebble.domain.FileManager:isUnderneathRootDirectory(...)@129: {1}, {0}
              *    org.apache.commons.fileupload.FileItem:getSize(...)@118: {-263..0}, {1..264-1}
              *    ...
              */
    75      Blog blog = (Blog)getModel().get(Constants.BLOG_KEY);
    76  
    77      String type = getType();
    78      String path = "";
    79      String[] filenames = new String[10];
    80  
    81      FileManager fileManager = new FileManager(blog, type);
    82  
    83      try {
    84        boolean isMultipart = FileUpload.isMultipartContent(request);
    85  
    86        if (isMultipart) {
    87          DiskFileUpload upload = new DiskFileUpload();
    88          long sizeInBytes = PebbleContext.getInstance().getConfiguration().getFileUploadSize() * 1024; // convert to bytes
    89          upload.setSizeMax(sizeInBytes);
    90          upload.setSizeThreshold((int)sizeInBytes/4);
    91          upload.setRepositoryPath(System.getProperty("java.io.tmpdir"));
    92  
    93          List items;
    94          try {
    95            items = upload.parseRequest(request);
    96          } catch (FileUploadBase.SizeLimitExceededException e) {
    97            return new FileTooLargeView();
    98          }
    99  
   100          // find the form fields first
   101          Iterator it = items.iterator();
   102          while (it.hasNext()) {
   103            FileItem item = (FileItem)it.next();
   104            if (item.isFormField() && item.getFieldName().startsWith("filename")) {
   105              int index = Integer.parseInt(item.getFieldName().substring(item.getFieldName().length()-1));
   106              filenames[index] = item.getString();
   107              log.debug("index is " + index + ", filename is " + filenames[index]);
   108            } else if (item.isFormField() && item.getFieldName().equals("path")) {
   109              path = item.getString();
   110            }
   111          }
   112  
   113          // now the actual files
   114          it = items.iterator();
   115          while (it.hasNext()) {
   116            FileItem item = (FileItem)it.next();
   117  
   118            if (!item.isFormField() && item.getSize() > 0 && item.getFieldName().startsWith("file")) {
   119              int index = Integer.parseInt(item.getFieldName().substring(item.getFieldName().length()-1));
   120  
   121              // if the filename hasn't been specified, use that from the file
   122              // being uploaded
   123              if (filenames[index] == null || filenames[index].length() == 0) {
   124                filenames[index] = item.getName();
   125              }
   126  
   127              File destinationDirectory = fileManager.getFile(path);
   128              File file = new File(destinationDirectory, filenames[index]);
   129              if (!fileManager.isUnderneathRootDirectory(file)) {
   130                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
   131                return null;
   132              }
   133  
   134              long itemSize = item.getSize()/1024;
   135              if (FileManager.hasEnoughSpace(blog, itemSize)) {
   136                log.debug("Writing file " + filenames[index] + ", size is " + item.getSize());
   137                writeFile(fileManager, path, filenames[index], item);
   138  
   139                // if it's a theme file, also create a copy in blog.dir/theme
   140                if (type.equals(FileMetaData.THEME_FILE)) {
   141                  writeFile(new FileManager(blog, FileMetaData.BLOG_DATA), "/theme" + path, filenames[index], item);
   142                }
   143              } else {
   144                return new NotEnoughSpaceView();
   145              }
   146            }
   147          }
   148        }
   149  
   150        blog.info("Files uploaded.");
   151      } catch (Exception e) {
   152        throw new ServletException(e);
   153      }
   154  
   155      FileMetaData directory = fileManager.getFileMetaData(path);
   156  
   157      return new RedirectView(blog.getUrl() + directory.getUrl());
   158    }
   159  
   160    /**
   161     * Helper method to write a file.
   162     *
   163     * @param fileManager   a FileManager instance
   164     * @param path          the path where to save the file
   165     * @param filename      the filename
   166     * @param item          the uploaded item
   167     * @throws Exception    if something goes wrong writing the file
   168     */
   169    private void writeFile(FileManager fileManager, String path, String filename, FileItem item) throws Exception {
             /* 
    P/P       *  Method: void writeFile(FileManager, String, String, FileItem)
              * 
              *  Preconditions:
              *    fileManager != null
              *    item != null
              * 
              *  Presumptions:
              *    net.sourceforge.pebble.domain.FileManager:getFile(...)@170 != null
              */
   170      File destinationDirectory = fileManager.getFile(path);
   171      destinationDirectory.mkdirs();
   172  
   173      File file = new File(destinationDirectory, filename);
   174      item.write(file);
   175    }
   176  
   177    /**
   178     * Gets the type of this upload (blog image, blog file or theme file).
   179     *
   180     * @return    a String representing the type
   181     * @see       net.sourceforge.pebble.domain.FileMetaData
   182     */
   183    protected abstract String getType();
   184  
   185    /**
   186     * Gets a list of all roles that are allowed to access this action.
   187     *
   188     * @return  an array of Strings representing role names
   189     */
   190    public abstract String[] getRoles(HttpServletRequest request);
   191  
   192  }








SofCheck Inspector Build Version : 2.22510
uploadfileaction.java 2010-Jun-25 19:40:34
uploadfileaction.class 2010-Jul-19 20:23:38