Estou com uma dúvida em Upload, é que a plicação não esta importanto uma classe para o programa a classe Log.
Pelo Amor de Deus se alguém tiver uma classe e jsp funcionando (UPLOAD) me mande, que já estou a 2 semanas atrás dessas classes e JSP, mas nehuma esta funcionando corretamente. Essas são as classes: package org.apache.commons.fileupload; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; / public interface FileItem extends Serializable { // ------------------------------- Methods from javax.activation.DataSource /** * Returns an [EMAIL PROTECTED] java.io.InputStream InputStream} that can be * used to retrieve the contents of the file. * * @return An [EMAIL PROTECTED] java.io.InputStream InputStream} that can be * used to retrieve the contents of the file. * * @exception IOException if an error occurs. */ InputStream getInputStream() throws IOException; /** * Returns the content type passed by the browser or <code>null</code> if * not defined. * * @return The content type passed by the browser or <code>null</code> if * not defined. */ String getContentType(); /** * Returns the original filename in the client's filesystem. * * @return The original filename in the client's filesystem. */ String getName(); // ----------------------------------------------------- Manifest constants /** * The maximal size of request that will have it's elements stored * in memory. */ public static final int DEFAULT_UPLOAD_SIZE_THRESHOLD = 10240; // ------------------------------------------------------- FileItem methods /** * Provides a hint as to whether or not the file contents will be read * from memory. * * @return <code>true</code> if the file contents will be read * from memory. */ boolean isInMemory(); /** * Returns the size of the file. * * @return The size of the file, in bytes. */ long getSize(); /** * Returns the contents of the file as an array of bytes. If the * contents of the file were not yet cached in memory, they will be * loaded from the disk storage and cached. * * @return The contents of the file as an array of bytes. */ byte[] get(); /** * Returns the contents of the file as a String, using the specified * encoding. This method uses [EMAIL PROTECTED] #get()} to retrieve the * contents of the file. * * @param encoding The character encoding to use. * * @return The contents of the file, as a string. * * @exception UnsupportedEncodingException if the requested character * encoding is not available. */ String getString(String encoding) throws UnsupportedEncodingException; /** * Returns the contents of the file as a String, using the default * character encoding. This method uses [EMAIL PROTECTED] #get()} to retrieve the * contents of the file. * * @return The contents of the file, as a string. */ String getString(); /** * Returns the [EMAIL PROTECTED] java.io.File} object for the <code>FileItem</code>'s * data's temporary location on the disk. Note that for * <code>FileItem</code>s that have their data stored in memory, * this method will return <code>null</code>. When handling large * files, you can use [EMAIL PROTECTED] java.io.File#renameTo(File)} to * move the file to new location without copying the data, if the * source and destination locations reside within the same logical * volume. * * @return The data file, or <code>null</code> if the data is stored in * memory. */ File getStoreLocation(); /** * A convenience method to write an uploaded file to disk. The client code * is not concerned whether or not the file is stored in memory, or on disk * in a temporary location. They just want to write the uploaded file to * disk. * * @param file The full path to location where the uploaded file should * be stored. * * @exception Exception if an error occurs. */ void write(String file) throws Exception; /** * Deletes the underlying storage for a file item, including deleting any * associated temporary disk file. Although this storage will be deleted * automatically when the <code>FileItem</code> instance is garbage * collected, this method can be used to ensure that this is done at an * earlier time, thus preserving system resources. */ void delete(); /** * Returns the name of the field in the multipart form corresponding to * this file item. * * @return The name of the form field. */ String getFieldName(); /** * Sets the field name used to reference this file item. * * @param name The name of the form field. */ void setFieldName(String name); /** * Determines whether or not a <code>FileItem</code> instance represents * a simple form field. * * @return <code>true</code> if the instance represents a simple form * field; <code>false</code> if it represents an uploaded file. */ boolean isFormField(); /** * Specifies whether or not a <code>FileItem</code> instance represents * a simple form field. * * @param state <code>true</code> if the instance represents a simple form * field; <code>false</code> if it represents an uploaded file. */ void setIsFormField(boolean state); public OutputStream getOutputStream() throws IOException; } /* * $Header: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/ FileUpload.java,v 1.15 2002/12/25 04:05:07 martinc Exp $ * $Revision: 1.15 $ * $Date: 2002/12/25 04:05:07 $ * * ==================================================================== * * 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 PROTECTED] * * 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; 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( contentType.indexOf("boundary=") + 9).getBytes(); InputStream input = (InputStream) req.getInputStream(); MultipartStream multi = new MultipartStream(input, boundary); boolean nextPart = multi.skipPreamble(); while (nextPart) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = getHeader(headers, CONTENT_TYPE); if (subContentType != null && subContentType .startsWith(MULTIPART_MIXED)) { // Multiple files. byte[] subBoundary = subContentType.substring( subContentType .indexOf("boundary=") + 9).getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(sizeThreshold, path, headers, requestSize); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } item.setFieldName(getFieldName(headers)); items.add(item); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); } else { if (getFileName(headers) != null) { // A single file. FileItem item = createItem(sizeThreshold, path, headers, requestSize); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } item.setFieldName(getFieldName(headers)); items.add(item); } else { // A form field. FileItem item = createItem(sizeThreshold, path, headers, requestSize); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } item.setFieldName(getFieldName(headers)); item.setIsFormField(true); items.add(item); } } } else { // Skip this part. multi.discardBodyData(); } nextPart = multi.readBoundary(); } } catch (IOException e) { throw new FileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage()); } return items; } // ------------------------------------------------------ Protected methods /** * Retrieves the file name from the <code>Content-disposition</code> * header. * * @param headers A <code>Map</code> containing the HTTP request headers. * * @return The file name for the current <code>encapsulation</code>. */ protected String getFileName(Map /* String, String */ headers) { String fileName = null; String cd = getHeader(headers, CONTENT_DISPOSITION); if (cd.startsWith(FORM_DATA) || cd.startsWith(ATTACHMENT)) { int start = cd.indexOf("filename=\""); int end = cd.indexOf('"', start + 10); if (start != -1 && end != -1) { fileName = cd.substring(start + 10, end).trim(); } } return fileName; } /** * Retrieves the field name from the <code>Content-disposition</code> * header. * * @param headers A <code>Map</code> containing the HTTP request headers. * * @return The field name for the current <code>encapsulation</code>. */ protected String getFieldName(Map /* String, String */ headers) { String fieldName = null; String cd = getHeader(headers, CONTENT_DISPOSITION); if (cd != null && cd.startsWith(FORM_DATA)) { int start = cd.indexOf("name=\""); int end = cd.indexOf('"', start + 6); if (start != -1 && end != -1) { fieldName = cd.substring(start + 6, end); } } return fieldName; } /** * Creates a new [EMAIL PROTECTED] org.apache.commons.fileupload.FileItem} instance. * * @param sizeThreshold The max size in bytes to be stored in memory. * @param path The path for the FileItem. * @param headers A <code>Map</code> containing the HTTP request * headers. * @param requestSize The total size of the request, in bytes. * * @return A newly created <code>FileItem</code> instance. * * @exception FileUploadException if an error occurs. */ protected FileItem createItem(int sizeThreshold, String path, Map /* String, String */ headers, int requestSize) throws FileUploadException { Method newInstanceMethod = getNewInstanceMethod(); Object[] args = new Object[] { path, getFileName(headers), getHeader(headers, CONTENT_TYPE), new Integer(requestSize), new Integer(sizeThreshold) }; FileItem fileItem = null; try { fileItem = (FileItem) newInstanceMethod.invoke(null, args); } catch (Exception e) { throw new FileUploadException(e.toString()); } return fileItem; } /** * <p> Returns the <code>Method</code> object to be used to obtain a new * <code>FileItem</code> instance. * * <p> For performance reasons, we cache the method once it has been * looked up, since method lookup is one of the more expensive aspects * of reflection. * * @return The <code>newInstance()</code> method to be invoked. * * @exception FileUploadException if an error occurs. */ protected Method getNewInstanceMethod() throws FileUploadException { // If the method is already cached, just return it. if (this.newInstanceMethod != null) { return this.newInstanceMethod; } // Load the FileUpload implementation class. ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class fileItemClass = null; if (classLoader == null) { classLoader = getClass().getClassLoader(); } try { fileItemClass = classLoader.loadClass(fileItemClassName); } catch (Exception e) { throw new FileUploadException(e.toString()); } if (fileItemClass == null) { throw new FileUploadException( "Failed to load FileItem class: " + fileItemClassName); } // Find the newInstance() method. Class[] parameterTypes = new Class[] { String.class, String.class, String.class, Integer.TYPE, Integer.TYPE }; Method newInstanceMethod = MethodUtils.getAccessibleMethod( fileItemClass, "newInstance", parameterTypes); if (newInstanceMethod == null) { throw new FileUploadException( "Failed find newInstance() method in FileItem class: " + fileItemClassName); } // Cache the method so that all this only happens once. this.newInstanceMethod = newInstanceMethod; return newInstanceMethod; } /** * <p> Parses the <code>header-part</code> and returns as key/value * pairs. * * <p> If there are multiple headers of the same names, the name * will map to a comma-separated list containing the values. * * @param headerPart The <code>header-part</code> of the current * <code>encapsulation</code>. * * @return A <code>Map</code> containing the parsed HTTP request headers. */ protected Map /* String, String */ parseHeaders(String headerPart) { Map headers = new HashMap(); char buffer[] = new char[MAX_HEADER_SIZE]; boolean done = false; int j = 0; int i; String header, headerName, headerValue; try { while (!done) { i = 0; // Copy a single line of characters into the buffer, // omitting trailing CRLF. while (i < 2 || buffer[i - 2] != '\r' || buffer[i - 1] != '\n') { buffer[i++] = headerPart.charAt(j++); } header = new String(buffer, 0, i - 2); if (header.equals("")) { done = true; } else { if (header.indexOf(':') == -1) { // This header line is malformed, skip it. continue; } headerName = header.substring(0, header.indexOf(':')) .trim().toLowerCase(); headerValue = header.substring(header.indexOf(':') + 1).trim(); if (getHeader(headers, headerName) != null) { // More that one heder of that name exists, // append to the list. headers.put(headerName, getHeader(headers, headerName) + ',' + headerValue); } else { headers.put(headerName, headerValue); } } } } catch (IndexOutOfBoundsException e) { // Headers were malformed. continue with all that was // parsed. } return headers; } /** * Returns the header with the specified name from the supplied map. The * header lookup is case-insensitive. * * @param headers A <code>Map</code> containing the HTTP request headers. * @param name The name of the header to return. * * @return The value of specified header, or a comma-separated list if * there were multiple headers of that name. */ protected final String getHeader(Map /* String, String */ headers, String name) { return (String) headers.get(name.toLowerCase()); } } upload exception: /* * $Header: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/ FileUploadException.java,v 1.6 2002/10/26 22:08:17 sullis Exp $ * $Revision: 1.6 $ * $Date: 2002/10/26 22:08:17 $ * * ==================================================================== * * 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 PROTECTED] * * 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; /** * Exception for errors encountered while processing the request. * * @author <a href="mailto:[EMAIL PROTECTED]">John McNally</a> * @version $Id: FileUploadException.java,v 1.6 2002/10/26 22:08:17 sullis Exp $ */ public class FileUploadException extends Exception { /** * Constructs a new <code>FileUploadException</code> without message. */ public FileUploadException() { } /** * Constructs a new <code>FileUploadException</code> with specified detail * message. * * @param msg the error message. */ public FileUploadException(String msg) { super(msg); } } outra classe: /* * $Header: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/ MultipartStream.java,v 1.9 2002/11/26 04:13:50 jericho Exp $ * $Revision: 1.9 $ * $Date: 2002/11/26 04:13:50 $ * * ==================================================================== * * 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 PROTECTED] * * 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.io.ByteArrayOutputStream; /** * <p> Low level API for processing file uploads. * * <p> This class can be used to process data streams conforming to MIME * 'multipart' format as defined in * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. Arbitrarily * large amounts of data in the stream can be processed under constant * memory usage. * * <p> The format of the stream is defined in the following way:<br> * * <code> * multipart-body := preamble 1*encapsulation close-delimiter epilogue<br> * encapsulation := delimiter body CRLF<br> * delimiter := "--" boundary CRLF<br> * close-delimiter := "--" boudary "--"<br> * preamble := <ignore><br> * epilogue := <ignore><br> * body := header-part CRLF body-part<br> * header-part := 1*header CRLF<br> * header := header-name ":" header-value<br> * header-name := <printable ascii characters except ":"><br> * header-value := <any ascii characters except CR & LF><br> * body-data := <arbitrary data><br> * </code> * * <p>Note that body-data can contain another mulipart entity. There * is limited support for single pass processing of such nested * streams. The nested stream is <strong>required</strong> to have a * boundary token of the same length as the parent stream (see [EMAIL PROTECTED] * #setBoundary(byte[])}). * * <p>Here is an exaple of usage of this class.<br> * * <pre> * try { * MultipartStream multipartStream = new MultipartStream(input, * boundary); * boolean nextPart = malitPartStream.skipPreamble(); * OutputStream output; * while(nextPart) { * header = chunks.readHeader(); * // process headers * // create some output stream * multipartStream.readBodyPart(output); * nextPart = multipartStream.readBoundary(); * } * } catch(MultipartStream.MalformedStreamException e) { * // the stream failed to follow required syntax * } catch(IOException) { * // a read or write error occurred * } * * </pre> * * @author <a href="mailto:[EMAIL PROTECTED]">Rafal Krzewski</a> * @author <a href="mailto:[EMAIL PROTECTED]">Martin Cooper</a> * * @version $Id: MultipartStream.java,v 1.9 2002/11/26 04:13:50 jericho Exp $ */ public class MultipartStream { // ----------------------------------------------------- Manifest constants /** * The maximum length of <code>header-part</code> that will be * processed (10 kilobytes = 10240 bytes.). */ public static final int HEADER_PART_SIZE_MAX = 10240; /** * The default length of the buffer used for processing a request. */ protected static final int DEFAULT_BUFSIZE = 4096; /** * A byte sequence that marks the end of <code>header-part</code> * (<code>CRLFCRLF</code>). */ protected static final byte[] HEADER_SEPARATOR = {0x0D, 0x0A, 0x0D, 0x0A}; /** * A byte sequence that that follows a delimiter that will be * followed by an encapsulation (<code>CRLF</code>). */ protected static final byte[] FIELD_SEPARATOR = { 0x0D, 0x0A }; /** * A byte sequence that that follows a delimiter of the last * encapsulation in the stream (<code>--</code>). */ protected static final byte[] STREAM_TERMINATOR = { 0x2D, 0x2D }; // ----------------------------------------------------------- Data members /** * The input stream from which data is read. */ private InputStream input; /** * The length of the boundary token plus the leading <code>CRLF--</code>. */ private int boundaryLength; /** * The amount of data, in bytes, that must be kept in the buffer in order * to detect delimiters reliably. */ private int keepRegion; /** * The byte sequence that partitions the stream. */ private byte[] boundary; /** * The length of the buffer used for processing the request. */ private int bufSize; /** * The buffer used for processing the request. */ private byte[] buffer; /** * The index of first valid character in the buffer. * <br> * 0 <= head < bufSize */ private int head; /** * The index of last valid characer in the buffer + 1. * <br> * 0 <= tail <= bufSize */ private int tail; // ----------------------------------------------------------- Constructors /** * Default constructor. */ public MultipartStream() { } /** * <p> Constructs a <code>MultipartStream</code> with a custom size buffer. * * <p> Note that the buffer must be at least big enough to contain the * boundary string, plus 4 characters for CR/LF and double dash, plus at * least one byte of data. Too small a buffer size setting will degrade * performance. * * @param input The <code>InputStream</code> to serve as a data source. * @param boundary The token used for dividing the stream into * <code>encapsulations</code>. * @param bufSize The size of the buffer to be used, in bytes. */ public MultipartStream(InputStream input, byte[] boundary, int bufSize) { this.input = input; this.bufSize = bufSize; this.buffer = new byte[bufSize]; // We prepend CR/LF to the boundary to chop trailng CR/LF from // body-data tokens. this.boundary = new byte[boundary.length + 4]; this.boundaryLength = boundary.length + 4; this.keepRegion = boundary.length + 3; this.boundary[0] = 0x0D; this.boundary[1] = 0x0A; this.boundary[2] = 0x2D; this.boundary[3] = 0x2D; System.arraycopy(boundary, 0, this.boundary, 4, boundary.length); head = 0; tail = 0; } /** * <p> Constructs a <code>MultipartStream</code> with a default size buffer. * * @param input The <code>InputStream</code> to serve as a data source. * @param boundary The token used for dividing the stream into * <code>encapsulations</code>. * * @exception IOException when an error occurs. */ public MultipartStream(InputStream input, byte[] boundary) throws IOException { this(input, boundary, DEFAULT_BUFSIZE); } // --------------------------------------------------------- Public methods /** * Reads a byte from the <code>buffer</code>, and refills it as * necessary. * * @return The next byte from the input stream. * * @exception IOException if there is no more data available. */ public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } } return buffer[head++]; } /** * Skips a <code>boundary</code> token, and checks whether more * <code>encapsulations</code> are contained in the stream. * * @return <code>true</code> if there are more encapsulations in * this stream; <code>false</code> otherwise. * * @exception MalformedStreamException if the stream ends unexpecetedly or * fails to follow required syntax. */ public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; } /** * <p>Changes the boundary token used for partitioning the stream. * * <p>This method allows single pass processing of nested multipart * streams. * * <p>The boundary token of the nested stream is <code>required</code> * to be of the same length as the boundary token in parent stream. * * <p>Restoring the parent stream boundary token after processing of a * nested stream is left to the application. * * @param boundary The boundary to be used for parsing of the nested * stream. * * @exception IllegalBoundaryException if the <code>boundary</code> * has a different length than the one * being currently parsed. */ public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - 4) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, 4, boundary.length); } /** * <p>Reads the <code>header-part</code> of the current * <code>encapsulation</code>. * * <p>Headers are returned verbatim to the input stream, including the * trailing <code>CRLF</code> marker. Parsing is left to the * application. * * <p><strong>TODO</strong> allow limiting maximum header size to * protect against abuse. * * @return The <code>header-part</code> of the current encapsulation. * * @exception MalformedStreamException if the stream ends unexpecetedly. */ public String readHeaders() throws MalformedStreamException { int i = 0; byte b[] = new byte[1]; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int sizeMax = HEADER_PART_SIZE_MAX; int size = 0; while (i < 4) { try { b[0] = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } size++; if (b[0] == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } if (size <= sizeMax) { baos.write(b[0]); } } return baos.toString(); } /** * <p>Reads <code>body-data</code> from the current * <code>encapsulation</code> and writes its contents into the * output <code>Stream</code>. * * <p>Arbitrary large amounts of data can be processed by this * method using a constant size buffer. (see [EMAIL PROTECTED] * #MultipartStream(InputStream,byte[],int) constructor}). * * @param output The <code>Stream</code> to write data into. * * @return the amount of data written. * * @exception MalformedStreamException if the stream ends unexpectedly. * @exception IOException if an i/o error occurs. */ public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { boolean done = false; int pad; int pos; int bytesRead; int total = 0; while (!done) { // Is boundary token present somewere in the buffer? pos = findSeparator(); if (pos != -1) { // Write the rest of the data before the boundary. output.write(buffer, head, pos - head); total += pos - head; head = pos; done = true; } else { // Determine how much data should be kept in the // buffer. if (tail - head > keepRegion) { pad = keepRegion; } else { pad = tail - head; } // Write out the data belonging to the body-data. output.write(buffer, head, tail - head - pad); // Move the data to the beging of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; bytesRead = input.read(buffer, pad, bufSize - pad); // [pprrrrrrr] if (bytesRead != -1) { tail = pad + bytesRead; } else { // The last pad amount is left in the buffer. // Boundary can't be in there so write out the // data you have and signal an error condition. output.write(buffer, 0, pad); output.flush(); total += pad; throw new MalformedStreamException( "Stream ended unexpectedly"); } } } output.flush(); return total; } /** * <p> Reads <code>body-data</code> from the current * <code>encapsulation</code> and discards it. * * <p>Use this method to skip encapsulations you don't need or don't * understand. * * @return The amount of data discarded. * * @exception MalformedStreamException if the stream ends unexpectedly. * @exception IOException if an i/o error occurs. */ public int discardBodyData() throws MalformedStreamException, IOException { boolean done = false; int pad; int pos; int bytesRead; int total = 0; while (!done) { // Is boundary token present somewere in the buffer? pos = findSeparator(); if (pos != -1) { // Write the rest of the data before the boundary. total += pos - head; head = pos; done = true; } else { // Determine how much data should be kept in the // buffer. if (tail - head > keepRegion) { pad = keepRegion; } else { pad = tail - head; } total += tail - head - pad; // Move the data to the beging of the buffer. System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; bytesRead = input.read(buffer, pad, bufSize - pad); // [pprrrrrrr] if (bytesRead != -1) { tail = pad + bytesRead; } else { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. total += pad; throw new MalformedStreamException( "Stream ended unexpectedly"); } } } return total; } /** * Finds the beginning of the first <code>encapsulation</code>. * * @return <code>true</code> if an <code>encapsulation</code> was found in * the stream. * * @exception IOException if an i/o error occurs. */ public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = 0x0D; boundary[1] = 0x0A; } } /** * Compares <code>count</code> first bytes in the arrays * <code>a</code> and <code>b</code>. * * @param a The first array to compare. * @param b The second array to compare. * @param count How many bytes should be compared. * * @return <code>true</code> if <code>count</code> first bytes in arrays * <code>a</code> and <code>b</code> are equal. */ public static boolean arrayequals(byte[] a, byte[] b, int count) { for (int i = 0; i < count; i++) { if (a[i] != b[i]) { return false; } } return true; } /** * Searches for a byte of specified value in the <code>buffer</code>, * starting at the specified <code>position</code>. * * @param value The value to find. * @param pos The starting position for searching. * * @return The position of byte found, counting from beginning of the * <code>buffer</code>, or <code>-1</code> if not found. */ protected int findByte(byte value, int pos) { for (int i = pos; i < tail; i++) { if (buffer[i] == value) { return i; } } return -1; } /** * Searches for the <code>boundary</code> in the <code>buffer</code> * region delimited by <code>head</code> and <code>tail</code>. * * @return The position of the boundary found, counting from the * beginning of the <code>buffer</code>, or <code>-1</code> if * not found. */ protected int findSeparator() { int first; int match = 0; int maxpos = tail - boundaryLength; for (first = head; (first <= maxpos) && (match != boundaryLength); first++) { first = findByte(boundary[0], first); if (first == -1 || (first > maxpos)) { return -1; } for (match = 1; match < boundaryLength; match++) { if (buffer[first + match] != boundary[match]) { break; } } } if (match == boundaryLength) { return first - 1; } return -1; } /** * Thrown to indicate that the input stream fails to follow the * required syntax. */ public class MalformedStreamException extends IOException { /** * Constructs a <code>MalformedStreamException</code> with no * detail message. */ public MalformedStreamException() { super(); } /** * Constructs an <code>MalformedStreamException</code> with * the specified detail message. * * @param message The detail message. */ public MalformedStreamException(String message) { super(message); } } /** * Thrown upon attempt of setting an invalid boundary token. */ public class IllegalBoundaryException extends IOException { /** * Constructs an <code>IllegalBoundaryException</code> with no * detail message. */ public IllegalBoundaryException() { super(); } /** * Constructs an <code>IllegalBoundaryException</code> with * the specified detail message. * * @param message The detail message. */ public IllegalBoundaryException(String message) { super(message); } } // ------------------------------------------------------ Debugging methods // These are the methods that were used to debug this stuff. /* // Dump data. protected void dump() { System.out.println("01234567890"); byte[] temp = new byte[buffer.length]; for(int i=0; i<buffer.length; i++) { if (buffer[i] == 0x0D || buffer[i] == 0x0A) { temp[i] = 0x21; } else { temp[i] = buffer[i]; } } System.out.println(new String(temp)); int i; for (i=0; i<head; i++) System.out.print(" "); System.out.println("h"); for (i=0; i<tail; i++) System.out.print(" "); System.out.println("t"); System.out.flush(); } // Main routine, for testing purposes only. // // @param args A String[] with the command line arguments. // @exception Exception, a generic exception. public static void main( String[] args ) throws Exception { File boundaryFile = new File("boundary.dat"); int boundarySize = (int)boundaryFile.length(); byte[] boundary = new byte[boundarySize]; FileInputStream input = new FileInputStream(boundaryFile); input.read(boundary,0,boundarySize); input = new FileInputStream("multipart.dat"); MultipartStream chunks = new MultipartStream(input, boundary); int i = 0; String header; OutputStream output; boolean nextChunk = chunks.skipPreamble(); while (nextChunk) { header = chunks.readHeaders(); System.out.println("!"+header+"!"); System.out.println("wrote part"+i+".dat"); output = new FileOutputStream("part"+(i++)+".dat"); chunks.readBodyData(output); nextChunk = chunks.readBoundary(); } } */ } Atenciosamente aguardando Salvação Conrad Peres. ----- Original Message ----- From: "SILVIO AMERICO GARCIA CICOTI" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Friday, June 27, 2003 8:14 AM Subject: RES: [java-list] to be EJB or not to be Cara...veja se você não esta "matando uma mosca com um canhão" ! Silvio. -----Mensagem original----- De: Daniel Bondance [mailto:[EMAIL PROTECTED] Enviada em: Wednesday, June 25, 2003 5:32 PM Para: '[EMAIL PROTECTED]' Assunto: RES: [java-list] to be EJB or not to be Para diser a verdade, uma boa dica é: utilize EJB´s sim. Claro que aos pôcapráticas com ele vai ser mais trabalhoso, mas depois que engrenar é muito útil e tranquilo. Uso há um tempo e não tem havido problema nenhum. danielbondance [EMAIL PROTECTED] highdesigners.com consultoria e desenvolvimento de softwares -----Mensagem original----- De: leonardo bruno [mailto:[EMAIL PROTECTED] Enviada em: terça-feira, 24 de junho de 2003 14:23 Para: [EMAIL PROTECTED] Assunto: Re: [java-list] to be EJB or not to be Pelo amor de Deus, eu desenvolvo, utilizando toda a plataforma J2EE, agora esse papo de que os EJB's nao sao bons!!!! é brincadeira, vcs deveriam ver que a partir da Especificacao 2.1 , melhorou muita coisa , eu por exemplo desenvolvo um Sistema de porte grande e para mim na minha opiniao os EJB's me dao total suporte para a minha impementacao!!!! Caro Joao , essa sua pergunta vai gerar muita polemica, pois os que conhecem bem a tecnologia irao te dizer que ela é muito boa e os que nao conhecem te diram que é melhor usar os servlets e os JSP's, eu particularmente utilizo toda a plataforma J2EE Sem mais leo >From: Agnaldo de Oliveira <[EMAIL PROTECTED]> >Reply-To: [EMAIL PROTECTED] >To: [EMAIL PROTECTED] >Subject: Re: [java-list] to be EJB or not to be >Date: Mon, 23 Jun 2003 08:38:37 -0300 > >Caro Joao Pedro, nossa experiencia diz que vc so deve usar EJB, quando >todas as suas opcoes em servlets, beans, se esgotarem, pois o tempo de >desenvolvimento e muito grande para desenvolver com EJB, ou seja vc caso >precise controlar tranzacoes em bancos de dados distribuidos, ou >diferentes, ou interagir com aplicacoes diferentes. ok. > >obs: meu linux ta com pau na acentuacao me desculpe. > >t mais... > >Agnaldo de Oliveira > >linux wrote: > >>Caros Amigos, >> >>Em um projeto que estou envolvido estamos em um ponto de decisao sobre >>adotar ou nao EJBs. >> >>Como nosso projeto tem um publico pequeno menos de 100 pessoas, visa >>performance, utilizacao otimizada dos recuros de hardware (que sao >>poucos) devo apontar as vantagens e desvantagens de se utilizar EJBs. >> >>Entao gostaria de fazer uma pergunta, levando-se em conta que: >> >>1) A performance eh fundamental, pois a massa de dados manipulada eh >>imensa. >>2) Nao havera processamento distribuido pois temos apenas >>uma maquina HP-UX 32 proc. >>3) O tempo de desenvolvimento do projeto eh muito curto. >>4) O numero de usuarios eh bem pequeno. >> >>Quais vantagens e desvantagens voces vem em se utilizar EJBs? >> >>Gostaria imensamente de saber as opinioes e experiencias de voces. >> >>Muito obrigado >> >>Joao Pedro >> >> >> >>------------------------------ LISTA SOUJAVA >>---------------------------- >>http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP >>dúvidas mais comuns: http://www.soujava.org.br/faq.htm >>regras da lista: http://www.soujava.org.br/regras.htm >>historico: http://www.mail-archive.com/java-list%40soujava.org.br >>para sair da lista: envie email para [EMAIL PROTECTED] >>------------------------------------------------------------------------- >> >> >> >> >> > > > >------------------------------ LISTA SOUJAVA >---------------------------- >http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP >dúvidas mais comuns: http://www.soujava.org.br/faq.htm >regras da lista: http://www.soujava.org.br/regras.htm >historico: http://www.mail-archive.com/java-list%40soujava.org.br >para sair da lista: envie email para [EMAIL PROTECTED] >------------------------------------------------------------------------- > _________________________________________________________________ MSN Messenger: converse com os seus amigos online. http://messenger.msn.com.br ------------------------------ LISTA SOUJAVA ---------------------------- http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] ------------------------------------------------------------------------- ------------------------------ LISTA SOUJAVA ---------------------------- http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] ------------------------------------------------------------------------- ***** Internet E-mail Confidentiality Footer ***** "Esta mensagem pode conter informações privilegiadas e/ou confidenciais de propriedades da BCP Telecomunicações. Caso voce não seja o destinatário ou pessoa autorizada a recebe-la não poderá utiliza-la de forma alguma. Cópia, revelação ou quaisquer outras ações baseadas nestas informações não são autorizadas. Se voce recebeu esta mensagem de forma equivocada, por favor informe o emissor imediatamente respondendo a este email e em seguida eliminando-o. Agradecemos sua cooperação." "This message may contain confidential and/or privileged information belong to BCP Telecomunications. If you are not the addressee or authorized to receive this for the addressee, you must not use, copy, disclose or take any action based on this message or any information herein. If you have received this message in error, please advise the sender immediately by reply e-mail and delete this message. Thank you for your cooperation." ------------------------------ LISTA SOUJAVA ---------------------------- http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] ------------------------------------------------------------------------- ------------------------------ LISTA SOUJAVA ---------------------------- http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] -------------------------------------------------------------------------