<commit_before>/*
 * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//fileupload/src/java/org/apache/commons/fileupload/FileUpload.java,v 1.13 2002/10/27 17:11:46 sullis Exp $
 * $Revision: 1.13 $
 * $Date: 2002/10/27 17:11:46 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact <EMAIL>.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */


package org.apache.commons.fileupload;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.MethodUtils;


/**
 * <p>High level API for processing file uploads.</p>
 *
 * <p>This class handles multiple files per single HTML widget, sent using
 * <code>multipart/mixed</code> encoding type, as specified by 
 * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>.  Use {@link
 * #parseRequest(HttpServletRequest)} to acquire a list of {@link
 * org.apache.commons.fileupload.FileItem}s associated with a given HTML
 * widget.</p>
 *
 * <p> Files will be stored in temporary disk storage or in memory,
 * depending on request size, and will be available as {@link
 * org.apache.commons.fileupload.FileItem}s.</p>
 *
 * @author <a href="mailto:Rafal.Krzew<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <NAME>
 *
 * @version $Id: FileUpload.java,v 1.13 2002/10/27 17:11:46 sullis Exp $
 */
public class FileUpload
{

    // ----------------------------------------------------- Manifest constants


    /**
     * HTTP content type header name.
     */
    public static final String CONTENT_TYPE = "Content-type";


    /**
     * HTTP content disposition header name.
     */
    public static final String CONTENT_DISPOSITION = "Content-disposition";


    /**
     * Content-disposition value for form data.
     */
    public static final String FORM_DATA = "form-data";


    /**
     * Content-disposition value for file attachment.
     */
    public static final String ATTACHMENT = "attachment";


    /**
     * Part of HTTP content type header.
     */
    private static final String MULTIPART = "multipart/";


    /**
     * HTTP content type header for multipart forms.
     */
    public static final String MULTIPART_FORM_DATA = "multipart/form-data";


    /**
     * HTTP content type header for multiple uploads.
     */
    public static final String MULTIPART_MIXED = "multipart/mixed";


    /**
     * The maximum length of a single header line that will be parsed
     * (1024 bytes).
     */
    public static final int MAX_HEADER_SIZE = 1024;


    // ----------------------------------------------------------- Data members


    /**
     * The maximum size permitted for an uploaded file.
     */
    private int sizeMax;


    /**
     * The threshold above which uploads will be stored on disk.
     */
    private int sizeThreshold;


    /**
     * The path to which uploaded files will be stored, if stored on disk.
     */
    private String repositoryPath;


    /**
     * The name of the class to use for <code>FileItem</code>s.
     */
    private String fileItemClassName =
            "org.apache.commons.fileupload.DefaultFileItem";


    /**
     * The cached method for obtaining a new <code>FileItem</code> instance.
     */
    private Method newInstanceMethod;
    

    // ----------------------------------------------------- Property accessors


    /**
     * Returns the maximum allowed upload size.
     *
     * @return The maximum allowed size, in bytes.
     * 
     * @see #setSizeMax(int)
     * 
     */
    public int getSizeMax() 
    {
        return sizeMax;
    }


    /**
     * Sets the maximum allowed upload size. If negative, there is no maximum.
     *
     * @param sizeMax The maximum allowed size, in bytes, or -1 for no maximum.
     * 
     * @see #getSizeMax()
     * 
     */
    public void setSizeMax(int sizeMax) 
    {
        this.sizeMax = sizeMax;
    }


    /**
     * Returns the size threshold beyond which files are written directly to
     * disk. The default value is 1024 bytes.
     *
     * @return The size threshold, in bytes.
     *
     * @see #setSizeThreshold(int)
     * 
     *
     */
    public int getSizeThreshold()
    {
        return sizeThreshold;
    }


    /**
     * Sets the size threshold beyond which files are written directly to disk.
     *
     * @param sizeThreshold The size threshold, in bytes.
     * 
     * @see #getSizeThreshold()
     * 
     */
    public void setSizeThreshold(int sizeThreshold) 
    {
        this.sizeThreshold = sizeThreshold;
    }


    /**
     * Returns the location used to temporarily store files that are larger
     * than the configured size threshold.
     *
     * @return The path to the temporary file location.
     * 
     * @see #setRepositoryPath(String)
     * 
     */
    public String getRepositoryPath()
    {
        return repositoryPath;
    }

    /**
     * Sets the location used to temporarily store files that are larger
     * than the configured size threshold.
     *
     * @param repositoryPath The path to the temporary file location.
     * 
     * @see #getRepositoryPath()
     * 
     */
    public void setRepositoryPath(String repositoryPath) 
    {
        this.repositoryPath = repositoryPath;
    }


    /**
     * Returns the fully qualified name of the class which will be used to
     * instantiate <code>FileItem</code> instances when a request is parsed.
     *
     * @return The fully qualified name of the Java class.
     * 
     * @see #setFileItemClassName(String)
     * 
     */
    public String getFileItemClassName()
    {
        return fileItemClassName;
    }


    /**
     * Sets the fully qualified name of the class which will be used to
     * instantiate <code>FileItem</code> instances when a request is parsed.
     *
     * @param fileItemClassName The fully qualified name of the Java class.
     * 
     * @see #getFileItemClassName()
     * 
     */
    public void setFileItemClassName(String fileItemClassName)
    {
        this.fileItemClassName = fileItemClassName;
        this.newInstanceMethod = null;
    }


    // --------------------------------------------------------- Public methods


    /**
     * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
     * compliant <code>multipart/form-data</code> stream. If files are stored
     * on disk, the path is given by <code>getRepositoryPath()</code>.
     *
     * @param req The servlet request to be parsed.
     *
     * @return A list of <code>FileItem</code> instances parsed from the
     *         request, in the order that they were transmitted.
     *
     * @exception FileUploadException if there are problems reading/parsing
     *                                the request or storing files.
     */
    public List /* FileItem */ parseRequest(HttpServletRequest req)
        throws FileUploadException
    {
        return parseRequest(req, getSizeThreshold(), getSizeMax(), 
                            getRepositoryPath());
    }


    /**
     * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
     * compliant <code>multipart/form-data</code> stream. If files are stored
     * on disk, the path is given by <code>getRepositoryPath()</code>.
     *
     * @param req           The servlet request to be parsed. Must be non-null.
     * @param sizeThreshold The max size in bytes to be stored in memory.
     * @param sizeMax       The maximum allowed upload size, in bytes.
     * @param path          The location where the files should be stored.
     *
     * @return A list of <code>FileItem</code> instances parsed from the
     *         request, in the order that they were transmitted.
     *
     * @exception FileUploadException if there are problems reading/parsing
     *                                the request or storing files.
     */
    public List /* FileItem */ parseRequest(HttpServletRequest req,
                                            int sizeThreshold, 
                                            int sizeMax, String path)
        throws FileUploadException
    {
    	if (null == req)
    	{
    		throw new NullPointerException("req parameter");
    	}
    	
        ArrayList items = new ArrayList();
        String contentType = req.getHeader(CONTENT_TYPE);

        if ( (null == contentType) || (!contentType.startsWith(MULTIPART)) )
        {
            throw new FileUploadException("the request doesn't contain a "
                + MULTIPART_FORM_DATA 
                + " or " 
                + MULTIPART_MIXED 
                + " stream, content type header is "
                + contentType);
        }
        int requestSize = req.getContentLength();

        if (requestSize == -1)
        {
            throw new FileUploadException("the request was rejected because " +
                "it's size is unknown");
        }

        if (sizeMax >= 0 && requestSize > sizeMax)
        {
            throw new FileUploadException("the request was rejected because " +
                "it's size exceeds allowed range");
        }

        try
        {
            byte[] boundary = contentType.substring(<commit_msg>Add isMultipartContent() method, per patch supplied by <NAME>, modified to satisfy coding guidelines. Thanks, Robert!<commit_after>/*
 * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//fileupload/src/java/org/apache/commons/fileupload/FileUpload.java,v 1.14 2002/11/10 06:31:10 martinc Exp $
 * $Revision: 1.14 $
 * $Date: 2002/11/10 06:31:10 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact <EMAIL>.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */


package org.apache.commons.fileupload;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.MethodUtils;


/**
 * <p>High level API for processing file uploads.</p>
 *
 * <p>This class handles multiple files per single HTML widget, sent using
 * <code>multipart/mixed</code> encoding type, as specified by 
 * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>.  Use {@link
 * #parseRequest(HttpServletRequest)} to acquire a list of {@link
 * org.apache.commons.fileupload.FileItem}s associated with a given HTML
 * widget.</p>
 *
 * <p> Files will be stored in temporary disk storage or in memory,
 * depending on request size, and will be available as {@link
 * org.apache.commons.fileupload.FileItem}s.</p>
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <NAME>
 *
 * @version $Id: FileUpload.java,v 1.14 2002/11/10 06:31:10 martinc Exp $
 */
public class FileUpload
{

    // ----------------------------------------------------- Class methods
    
    /**
     * Utility method that determines whether the request contains multipart
     * content.
     *
     * @param req The servlet request to be evaluated. Must be non-null.
     *
     * @return <code>true</code> if the request is multipart;
     *         <code>false</code> otherwise.
     */
    public static final boolean isMultipartContent(HttpServletRequest req) 
    {
        String contentType = req.getHeader(CONTENT_TYPE);
        if (contentType == null) 
        {
            return false;
        }
        if (contentType.startsWith(MULTIPART))
        {
            return true;
        }
        return false;
    }
    

    // ----------------------------------------------------- Manifest constants


    /**
     * HTTP content type header name.
     */
    public static final String CONTENT_TYPE = "Content-type";


    /**
     * HTTP content disposition header name.
     */
    public static final String CONTENT_DISPOSITION = "Content-disposition";


    /**
     * Content-disposition value for form data.
     */
    public static final String FORM_DATA = "form-data";


    /**
     * Content-disposition value for file attachment.
     */
    public static final String ATTACHMENT = "attachment";


    /**
     * Part of HTTP content type header.
     */
    private static final String MULTIPART = "multipart/";


    /**
     * HTTP content type header for multipart forms.
     */
    public static final String MULTIPART_FORM_DATA = "multipart/form-data";


    /**
     * HTTP content type header for multiple uploads.
     */
    public static final String MULTIPART_MIXED = "multipart/mixed";


    /**
     * The maximum length of a single header line that will be parsed
     * (1024 bytes).
     */
    public static final int MAX_HEADER_SIZE = 1024;


    // ----------------------------------------------------------- Data members


    /**
     * The maximum size permitted for an uploaded file.
     */
    private int sizeMax;


    /**
     * The threshold above which uploads will be stored on disk.
     */
    private int sizeThreshold;


    /**
     * The path to which uploaded files will be stored, if stored on disk.
     */
    private String repositoryPath;


    /**
     * The name of the class to use for <code>FileItem</code>s.
     */
    private String fileItemClassName =
            "org.apache.commons.fileupload.DefaultFileItem";


    /**
     * The cached method for obtaining a new <code>FileItem</code> instance.
     */
    private Method newInstanceMethod;
    

    // ----------------------------------------------------- Property accessors


    /**
     * Returns the maximum allowed upload size.
     *
     * @return The maximum allowed size, in bytes.
     * 
     * @see #setSizeMax(int)
     * 
     */
    public int getSizeMax() 
    {
        return sizeMax;
    }


    /**
     * Sets the maximum allowed upload size. If negative, there is no maximum.
     *
     * @param sizeMax The maximum allowed size, in bytes, or -1 for no maximum.
     * 
     * @see #getSizeMax()
     * 
     */
    public void setSizeMax(int sizeMax) 
    {
        this.sizeMax = sizeMax;
    }


    /**
     * Returns the size threshold beyond which files are written directly to
     * disk. The default value is 1024 bytes.
     *
     * @return The size threshold, in bytes.
     *
     * @see #setSizeThreshold(int)
     * 
     *
     */
    public int getSizeThreshold()
    {
        return sizeThreshold;
    }


    /**
     * Sets the size threshold beyond which files are written directly to disk.
     *
     * @param sizeThreshold The size threshold, in bytes.
     * 
     * @see #getSizeThreshold()
     * 
     */
    public void setSizeThreshold(int sizeThreshold) 
    {
        this.sizeThreshold = sizeThreshold;
    }


    /**
     * Returns the location used to temporarily store files that are larger
     * than the configured size threshold.
     *
     * @return The path to the temporary file location.
     * 
     * @see #setRepositoryPath(String)
     * 
     */
    public String getRepositoryPath()
    {
        return repositoryPath;
    }

    /**
     * Sets the location used to temporarily store files that are larger
     * than the configured size threshold.
     *
     * @param repositoryPath The path to the temporary file location.
     * 
     * @see #getRepositoryPath()
     * 
     */
    public void setRepositoryPath(String repositoryPath) 
    {
        this.repositoryPath = repositoryPath;
    }


    /**
     * Returns the fully qualified name of the class which will be used to
     * instantiate <code>FileItem</code> instances when a request is parsed.
     *
     * @return The fully qualified name of the Java class.
     * 
     * @see #setFileItemClassName(String)
     * 
     */
    public String getFileItemClassName()
    {
        return fileItemClassName;
    }


    /**
     * Sets the fully qualified name of the class which will be used to
     * instantiate <code>FileItem</code> instances when a request is parsed.
     *
     * @param fileItemClassName The fully qualified name of the Java class.
     * 
     * @see #getFileItemClassName()
     * 
     */
    public void setFileItemClassName(String fileItemClassName)
    {
        this.fileItemClassName = fileItemClassName;
        this.newInstanceMethod = null;
    }


    // --------------------------------------------------------- Public methods

    /**
     * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
     * compliant <code>multipart/form-data</code> stream. If files are stored
     * on disk, the path is given by <code>getRepositoryPath()</code>.
     *
     * @param req The servlet request to be parsed.
     *
     * @return A list of <code>FileItem</code> instances parsed from the
     *         request, in the order that they were transmitted.
     *
     * @exception FileUploadException if there are problems reading/parsing
     *                                the request or storing files.
     */
    public List /* FileItem */ parseRequest(HttpServletRequest req)
        throws FileUploadException
    {
        return parseRequest(req, getSizeThreshold(), getSizeMax(), 
                            getRepositoryPath());
    }


    /**
     * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
     * compliant <code>multipart/form-data</code> stream. If files are stored
     * on disk, the path is given by <code>getRepositoryPath()</code>.
     *
     * @param req           The servlet request to be parsed. Must be non-null.
     * @param sizeThreshold The max size in bytes to be stored in memory.
     * @param sizeMax       The maximum allowed upload size, in bytes.
     * @param path          The location where the files should be stored.
     *
     * @return A list of <code>FileItem</code> instances parsed from the
     *         request, in the order that they were transmitted.
     *
     * @exception FileUploadException if there are problems reading/parsing
     *                                the request or storing files.
     */
    public List /* FileItem */ parseRequest(HttpServletRequest req,
                                            int sizeThreshold, 
                                            int sizeMax, String path)
        throws FileUploadException
    {
        if (null == req)
        {
            throw new NullPointerException("req parameter");
        }

        ArrayList items = new ArrayList();
        String contentType = req.getHeader(CONTENT_TYPE);

        if ((null == contentType) || (!contentType.startsWith(MULTIPART)))
        {
            throw new FileUploadException("the request doesn't contain a "
                + MULTIPART_FORM_DATA 
                + " or " 
                + MULTIPART_MIXED 
                + " stream, content type header is "
                + contentType);
        }
        int requestSize = req.getContentLength();

        if (requestSize == -1)
        {
            throw new FileUploadException("the request was rejected because " +
                "it's size is unknown");
        }

        if (sizeMax >= 0 && requestSize > sizeMax)
        {
            throw new FileUploadException("the request was rejected because " +
                "it's size exceeds allowed range");
        }

        try
        {
            byte[] boundary = contentType.substring(
{'fraction_non_alphanumeric': 0.11870316194445557, 'fraction_numerical': 0.008415821744880375, 'mean_word_length': 2.2687974849358135, 'pattern_counts': {'":': 0, '<': 122, '<?xml version=': 0, '>': 126, 'https://': 0, 'lorem ipsum': 0, 'www.': 10, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1688600', 'n_tokens_mistral': 6878, 'n_tokens_neox': 6379, 'n_words': 2325}