You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by ma...@apache.org on 2004/10/29 06:17:23 UTC
cvs commit: jakarta-commons/fileupload/src/java/org/apache/commons/fileupload DefaultFileItem.java DefaultFileItemFactory.java DiskFileUpload.java FileItem.java FileItemFactory.java FileUpload.java FileUploadBase.java FileUploadException.java MultipartStream.java ParameterParser.java
martinc 2004/10/28 21:17:23
Modified: fileupload project.properties
fileupload/src/java/org/apache/commons/fileupload
DefaultFileItem.java DefaultFileItemFactory.java
DiskFileUpload.java FileItem.java
FileItemFactory.java FileUpload.java
FileUploadBase.java FileUploadException.java
MultipartStream.java ParameterParser.java
Added: fileupload license-header.txt
Log:
Convert to Sun coding guidelines.
Revision Changes Path
1.8 +2 -1 jakarta-commons/fileupload/project.properties
Index: project.properties
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/project.properties,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- project.properties 25 Feb 2004 21:07:12 -0000 1.7
+++ project.properties 29 Oct 2004 04:17:23 -0000 1.8
@@ -20,7 +20,8 @@
compile.optimize = off
compile.deprecation = off
-maven.checkstyle.format = turbine
+maven.checkstyle.header.file=${basedir}/license-header.txt
+maven.javadoc.additionalparam=-tag todo:a:"To Do:"
maven.linkcheck.enable=true
# documentation properties
1.1 jakarta-commons/fileupload/license-header.txt
Index: license-header.txt
===================================================================
/*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
1.28 +84 -145 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DefaultFileItem.java
Index: DefaultFileItem.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DefaultFileItem.java,v
retrieving revision 1.27
retrieving revision 1.28
diff -u -r1.27 -r1.28
--- DefaultFileItem.java 12 Oct 2004 04:17:27 -0000 1.27
+++ DefaultFileItem.java 29 Oct 2004 04:17:23 -0000 1.28
@@ -53,8 +53,25 @@
* @version $Id$
*/
public class DefaultFileItem
- implements FileItem
-{
+ implements FileItem {
+
+ // ----------------------------------------------------- Manifest constants
+
+
+ /**
+ * Default content charset to be used when no explicit charset
+ * parameter is provided by the sender. Media subtypes of the
+ * "text" type are defined to have a default charset value of
+ * "ISO-8859-1" when received via HTTP.
+ */
+ public static final String DEFAULT_CHARSET = "ISO-8859-1";
+
+
+ /**
+ * Size of buffer to use when writing an item to disk.
+ */
+ private static final int WRITE_BUFFER_SIZE = 2048;
+
// ----------------------------------------------------------- Data members
@@ -72,15 +89,6 @@
/**
- * Default content charset to be used when no explicit charset
- * parameter is provided by the sender. Media subtypes of the
- * "text" type are defined to have a default charset value of
- * "ISO-8859-1" when received via HTTP.
- */
- public static final String DEFAULT_CHARSET = "ISO-8859-1";
-
-
- /**
* The content type passed by the browser, or <code>null</code> if
* not defined.
*/
@@ -144,8 +152,7 @@
* exceed the threshold.
*/
DefaultFileItem(String fieldName, String contentType, boolean isFormField,
- String fileName, int sizeThreshold, File repository)
- {
+ String fileName, int sizeThreshold, File repository) {
this.fieldName = fieldName;
this.contentType = contentType;
this.isFormField = isFormField;
@@ -168,15 +175,12 @@
* @exception IOException if an error occurs.
*/
public InputStream getInputStream()
- throws IOException
- {
- if (!dfos.isInMemory())
- {
+ throws IOException {
+ if (!dfos.isInMemory()) {
return new FileInputStream(dfos.getFile());
}
- if (cachedContent == null)
- {
+ if (cachedContent == null) {
cachedContent = dfos.getData();
}
return new ByteArrayInputStream(cachedContent);
@@ -190,8 +194,7 @@
* @return The content type passed by the agent or <code>null</code> if
* not defined.
*/
- public String getContentType()
- {
+ public String getContentType() {
return contentType;
}
@@ -199,17 +202,16 @@
/**
* Returns the content charset passed by the agent or <code>null</code> if
* not defined.
- *
+ *
* @return The content charset passed by the agent or <code>null</code> if
* not defined.
*/
- public String getCharSet()
- {
+ public String getCharSet() {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(getContentType(), ';');
- return (String)params.get("charset");
+ return (String) params.get("charset");
}
@@ -218,8 +220,7 @@
*
* @return The original filename in the client's filesystem.
*/
- public String getName()
- {
+ public String getName() {
return fileName;
}
@@ -234,8 +235,7 @@
* @return <code>true</code> if the file contents will be read
* from memory; <code>false</code> otherwise.
*/
- public boolean isInMemory()
- {
+ public boolean isInMemory() {
return (dfos.isInMemory());
}
@@ -245,18 +245,12 @@
*
* @return The size of the file, in bytes.
*/
- public long getSize()
- {
- if (cachedContent != null)
- {
+ public long getSize() {
+ if (cachedContent != null) {
return cachedContent.length;
- }
- else if (dfos.isInMemory())
- {
+ } else if (dfos.isInMemory()) {
return dfos.getData().length;
- }
- else
- {
+ } else {
return dfos.getFile().length();
}
}
@@ -269,12 +263,9 @@
*
* @return The contents of the file as an array of bytes.
*/
- public byte[] get()
- {
- if (dfos.isInMemory())
- {
- if (cachedContent == null)
- {
+ public byte[] get() {
+ if (dfos.isInMemory()) {
+ if (cachedContent == null) {
cachedContent = dfos.getData();
}
return cachedContent;
@@ -283,25 +274,16 @@
byte[] fileData = new byte[(int) getSize()];
FileInputStream fis = null;
- try
- {
+ try {
fis = new FileInputStream(dfos.getFile());
fis.read(fileData);
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
fileData = null;
- }
- finally
- {
- if (fis != null)
- {
- try
- {
+ } finally {
+ if (fis != null) {
+ try {
fis.close();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
// ignore
}
}
@@ -324,8 +306,7 @@
* encoding is not available.
*/
public String getString(final String charset)
- throws UnsupportedEncodingException
- {
+ throws UnsupportedEncodingException {
return new String(get(), charset);
}
@@ -336,20 +317,18 @@
* contents of the file.
*
* @return The contents of the file, as a string.
+ *
+ * @todo Consider making this method throw UnsupportedEncodingException.
*/
- public String getString()
- //@TODO: Consider making this method throw UnsupportedEncodingException
- {
+ public String getString() {
byte[] rawdata = get();
String charset = getCharSet();
if (charset == null) {
charset = DEFAULT_CHARSET;
}
- try
- {
+ try {
return new String(rawdata, charset);
- }
- catch(UnsupportedEncodingException e) {
+ } catch (UnsupportedEncodingException e) {
return new String(rawdata);
}
}
@@ -375,80 +354,56 @@
*
* @exception Exception if an error occurs.
*/
- public void write(File file) throws Exception
- {
- if (isInMemory())
- {
+ public void write(File file) throws Exception {
+ if (isInMemory()) {
FileOutputStream fout = null;
- try
- {
+ try {
fout = new FileOutputStream(file);
fout.write(get());
- }
- finally
- {
- if (fout != null)
- {
+ } finally {
+ if (fout != null) {
fout.close();
}
}
- }
- else
- {
+ } else {
File outputFile = getStoreLocation();
- if (outputFile != null)
- {
+ if (outputFile != null) {
/*
* The uploaded file is being stored on disk
* in a temporary location so move it to the
* desired file.
*/
- if (!outputFile.renameTo(file))
- {
+ if (!outputFile.renameTo(file)) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
- try
- {
+ try {
in = new BufferedInputStream(
new FileInputStream(outputFile));
out = new BufferedOutputStream(
new FileOutputStream(file));
- byte[] bytes = new byte[2048];
+ byte[] bytes = new byte[WRITE_BUFFER_SIZE];
int s = 0;
- while ((s = in.read(bytes)) != -1)
- {
+ while ((s = in.read(bytes)) != -1) {
out.write(bytes, 0, s);
}
- }
- finally
- {
- if (in != null)
- {
- try
- {
+ } finally {
+ if (in != null) {
+ try {
in.close();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
// ignore
}
}
- if (out != null)
- {
- try
- {
+ if (out != null) {
+ try {
out.close();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
// ignore
}
}
}
}
- }
- else
- {
+ } else {
/*
* For whatever reason we cannot write the
* file to disk.
@@ -467,12 +422,10 @@
* collected, this method can be used to ensure that this is done at an
* earlier time, thus preserving system resources.
*/
- public void delete()
- {
+ public void delete() {
cachedContent = null;
File outputFile = getStoreLocation();
- if (outputFile != null && outputFile.exists())
- {
+ if (outputFile != null && outputFile.exists()) {
outputFile.delete();
}
}
@@ -487,8 +440,7 @@
* @see #setFieldName(java.lang.String)
*
*/
- public String getFieldName()
- {
+ public String getFieldName() {
return fieldName;
}
@@ -501,8 +453,7 @@
* @see #getFieldName()
*
*/
- public void setFieldName(String fieldName)
- {
+ public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
@@ -517,8 +468,7 @@
* @see #setFormField(boolean)
*
*/
- public boolean isFormField()
- {
+ public boolean isFormField() {
return isFormField;
}
@@ -533,8 +483,7 @@
* @see #isFormField()
*
*/
- public void setFormField(boolean state)
- {
+ public void setFormField(boolean state) {
isFormField = state;
}
@@ -549,10 +498,8 @@
* @exception IOException if an error occurs.
*/
public OutputStream getOutputStream()
- throws IOException
- {
- if (dfos == null)
- {
+ throws IOException {
+ if (dfos == null) {
File outputFile = getTempFile();
dfos = new DeferredFileOutputStream(sizeThreshold, outputFile);
}
@@ -576,8 +523,7 @@
* @return The data file, or <code>null</code> if the data is stored in
* memory.
*/
- public File getStoreLocation()
- {
+ public File getStoreLocation() {
return dfos.getFile();
}
@@ -588,12 +534,10 @@
/**
* Removes the file contents from the temporary storage.
*/
- protected void finalize()
- {
+ protected void finalize() {
File outputFile = dfos.getFile();
- if (outputFile != null && outputFile.exists())
- {
+ if (outputFile != null && outputFile.exists()) {
outputFile.delete();
}
}
@@ -607,11 +551,9 @@
*
* @return The {@link java.io.File File} to be used for temporary storage.
*/
- protected File getTempFile()
- {
+ protected File getTempFile() {
File tempDir = repository;
- if (tempDir == null)
- {
+ if (tempDir == null) {
tempDir = new File(System.getProperty("java.io.tmpdir"));
}
@@ -632,19 +574,16 @@
*
* @return A String with the non-random looking instance identifier.
*/
- private static String getUniqueId()
- {
+ private static String getUniqueId() {
int current;
- synchronized (DefaultFileItem.class)
- {
+ synchronized (DefaultFileItem.class) {
current = counter++;
}
String id = Integer.toString(current);
// If you manage to get more than 100 million of ids, you'll
// start getting ids longer than 8 characters.
- if (current < 100000000)
- {
+ if (current < 100000000) {
id = ("00000000" + id).substring(id.length());
}
return id;
1.5 +9 -17 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DefaultFileItemFactory.java
Index: DefaultFileItemFactory.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DefaultFileItemFactory.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- DefaultFileItemFactory.java 25 Feb 2004 21:07:12 -0000 1.4
+++ DefaultFileItemFactory.java 29 Oct 2004 04:17:23 -0000 1.5
@@ -39,8 +39,7 @@
*
* @version $Id$
*/
-public class DefaultFileItemFactory implements FileItemFactory
-{
+public class DefaultFileItemFactory implements FileItemFactory {
// ----------------------------------------------------- Manifest constants
@@ -73,8 +72,7 @@
* Constructs an unconfigured instance of this class. The resulting factory
* may be configured by calling the appropriate setter methods.
*/
- public DefaultFileItemFactory()
- {
+ public DefaultFileItemFactory() {
}
@@ -88,8 +86,7 @@
* which files will be created, should the item size
* exceed the threshold.
*/
- public DefaultFileItemFactory(int sizeThreshold, File repository)
- {
+ public DefaultFileItemFactory(int sizeThreshold, File repository) {
this.sizeThreshold = sizeThreshold;
this.repository = repository;
}
@@ -107,8 +104,7 @@
* @see #setRepository(java.io.File)
*
*/
- public File getRepository()
- {
+ public File getRepository() {
return repository;
}
@@ -122,8 +118,7 @@
* @see #getRepository()
*
*/
- public void setRepository(File repository)
- {
+ public void setRepository(File repository) {
this.repository = repository;
}
@@ -136,8 +131,7 @@
*
* @see #setSizeThreshold(int)
*/
- public int getSizeThreshold()
- {
+ public int getSizeThreshold() {
return sizeThreshold;
}
@@ -150,8 +144,7 @@
* @see #getSizeThreshold()
*
*/
- public void setSizeThreshold(int sizeThreshold)
- {
+ public void setSizeThreshold(int sizeThreshold) {
this.sizeThreshold = sizeThreshold;
}
@@ -177,8 +170,7 @@
String contentType,
boolean isFormField,
String fileName
- )
- {
+ ) {
return new DefaultFileItem(fieldName, contentType,
isFormField, fileName, sizeThreshold, repository);
}
1.6 +11 -21 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DiskFileUpload.java
Index: DiskFileUpload.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/DiskFileUpload.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- DiskFileUpload.java 25 Feb 2004 21:07:12 -0000 1.5
+++ DiskFileUpload.java 29 Oct 2004 04:17:23 -0000 1.6
@@ -43,8 +43,7 @@
* @version $Id$
*/
public class DiskFileUpload
- extends FileUploadBase
- {
+ extends FileUploadBase {
// ----------------------------------------------------------- Data members
@@ -64,8 +63,7 @@
*
* @see #DiskFileUpload(DefaultFileItemFactory fileItemFactory)
*/
- public DiskFileUpload()
- {
+ public DiskFileUpload() {
super();
this.fileItemFactory = new DefaultFileItemFactory();
}
@@ -77,8 +75,7 @@
*
* @see #DiskFileUpload()
*/
- public DiskFileUpload(DefaultFileItemFactory fileItemFactory)
- {
+ public DiskFileUpload(DefaultFileItemFactory fileItemFactory) {
super();
this.fileItemFactory = fileItemFactory;
}
@@ -92,8 +89,7 @@
*
* @return The factory class for new file items.
*/
- public FileItemFactory getFileItemFactory()
- {
+ public FileItemFactory getFileItemFactory() {
return fileItemFactory;
}
@@ -105,8 +101,7 @@
*
* @param factory The factory class for new file items.
*/
- public void setFileItemFactory(FileItemFactory factory)
- {
+ public void setFileItemFactory(FileItemFactory factory) {
this.fileItemFactory = (DefaultFileItemFactory) factory;
}
@@ -119,8 +114,7 @@
*
* @see #setSizeThreshold(int)
*/
- public int getSizeThreshold()
- {
+ public int getSizeThreshold() {
return fileItemFactory.getSizeThreshold();
}
@@ -132,8 +126,7 @@
*
* @see #getSizeThreshold()
*/
- public void setSizeThreshold(int sizeThreshold)
- {
+ public void setSizeThreshold(int sizeThreshold) {
fileItemFactory.setSizeThreshold(sizeThreshold);
}
@@ -146,8 +139,7 @@
*
* @see #setRepositoryPath(String)
*/
- public String getRepositoryPath()
- {
+ public String getRepositoryPath() {
return fileItemFactory.getRepository().getPath();
}
@@ -160,8 +152,7 @@
*
* @see #getRepositoryPath()
*/
- public void setRepositoryPath(String repositoryPath)
- {
+ public void setRepositoryPath(String repositoryPath) {
fileItemFactory.setRepository(new File(repositoryPath));
}
@@ -188,8 +179,7 @@
public List /* FileItem */ parseRequest(HttpServletRequest req,
int sizeThreshold,
long sizeMax, String path)
- throws FileUploadException
- {
+ throws FileUploadException {
setSizeThreshold(sizeThreshold);
setSizeMax(sizeMax);
setRepositoryPath(path);
1.18 +2 -3 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileItem.java
Index: FileItem.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileItem.java,v
retrieving revision 1.17
retrieving revision 1.18
diff -u -r1.17 -r1.18
--- FileItem.java 25 Feb 2004 21:07:12 -0000 1.17
+++ FileItem.java 29 Oct 2004 04:17:23 -0000 1.18
@@ -50,8 +50,7 @@
* @version $Id$
*/
public interface FileItem
- extends Serializable
-{
+ extends Serializable {
// ------------------------------- Methods from javax.activation.DataSource
1.4 +3 -4 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileItemFactory.java
Index: FileItemFactory.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileItemFactory.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- FileItemFactory.java 25 Feb 2004 21:07:12 -0000 1.3
+++ FileItemFactory.java 29 Oct 2004 04:17:23 -0000 1.4
@@ -22,11 +22,10 @@
* by the default file upload implementation.</p>
*
* @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
- *
+ *
* @version $Id$
*/
-public interface FileItemFactory
-{
+public interface FileItemFactory {
/**
* Create a new {@link FileItem} instance from the supplied parameters and
1.27 +6 -11 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUpload.java
Index: FileUpload.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUpload.java,v
retrieving revision 1.26
retrieving revision 1.27
diff -u -r1.26 -r1.27
--- FileUpload.java 25 Feb 2004 21:07:12 -0000 1.26
+++ FileUpload.java 29 Oct 2004 04:17:23 -0000 1.27
@@ -39,8 +39,7 @@
* @version $Id$
*/
public class FileUpload
- extends FileUploadBase
- {
+ extends FileUploadBase {
// ----------------------------------------------------------- Data members
@@ -61,8 +60,7 @@
*
* @see #FileUpload(FileItemFactory)
*/
- public FileUpload()
- {
+ public FileUpload() {
super();
}
@@ -73,8 +71,7 @@
*
* @see #FileUpload()
*/
- public FileUpload(FileItemFactory fileItemFactory)
- {
+ public FileUpload(FileItemFactory fileItemFactory) {
super();
this.fileItemFactory = fileItemFactory;
}
@@ -88,8 +85,7 @@
*
* @return The factory class for new file items.
*/
- public FileItemFactory getFileItemFactory()
- {
+ public FileItemFactory getFileItemFactory() {
return fileItemFactory;
}
@@ -99,8 +95,7 @@
*
* @param factory The factory class for new file items.
*/
- public void setFileItemFactory(FileItemFactory factory)
- {
+ public void setFileItemFactory(FileItemFactory factory) {
this.fileItemFactory = factory;
}
1.11 +65 -133 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUploadBase.java
Index: FileUploadBase.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUploadBase.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- FileUploadBase.java 16 Oct 2004 18:17:50 -0000 1.10
+++ FileUploadBase.java 29 Oct 2004 04:17:23 -0000 1.11
@@ -47,8 +47,7 @@
*
* @version $Id$
*/
-public abstract class FileUploadBase
-{
+public abstract class FileUploadBase {
// ---------------------------------------------------------- Class methods
@@ -62,19 +61,15 @@
* @return <code>true</code> if the request is multipart;
* <code>false</code> otherwise.
*/
- public static final boolean isMultipartContent(HttpServletRequest req)
- {
- if (!"post".equals(req.getMethod().toLowerCase()))
- {
+ public static final boolean isMultipartContent(HttpServletRequest req) {
+ if (!"post".equals(req.getMethod().toLowerCase())) {
return false;
}
String contentType = req.getHeader(CONTENT_TYPE);
- if (contentType == null)
- {
+ if (contentType == null) {
return false;
}
- if (contentType.toLowerCase().startsWith(MULTIPART))
- {
+ if (contentType.toLowerCase().startsWith(MULTIPART)) {
return true;
}
return false;
@@ -176,8 +171,7 @@
* @see #setSizeMax(long)
*
*/
- public long getSizeMax()
- {
+ public long getSizeMax() {
return sizeMax;
}
@@ -190,8 +184,7 @@
* @see #getSizeMax()
*
*/
- public void setSizeMax(long sizeMax)
- {
+ public void setSizeMax(long sizeMax) {
this.sizeMax = sizeMax;
}
@@ -203,8 +196,7 @@
*
* @return The encoding used to read part headers.
*/
- public String getHeaderEncoding()
- {
+ public String getHeaderEncoding() {
return headerEncoding;
}
@@ -216,8 +208,7 @@
*
* @param encoding The encoding used to read part headers.
*/
- public void setHeaderEncoding(String encoding)
- {
+ public void setHeaderEncoding(String encoding) {
headerEncoding = encoding;
}
@@ -239,10 +230,8 @@
* the request or storing files.
*/
public List /* FileItem */ parseRequest(HttpServletRequest req)
- throws FileUploadException
- {
- if (null == req)
- {
+ throws FileUploadException {
+ if (null == req) {
throw new NullPointerException("req parameter");
}
@@ -250,8 +239,7 @@
String contentType = req.getHeader(CONTENT_TYPE);
if ((null == contentType)
- || (!contentType.toLowerCase().startsWith(MULTIPART)))
- {
+ || (!contentType.toLowerCase().startsWith(MULTIPART))) {
throw new InvalidContentTypeException(
"the request doesn't contain a "
+ MULTIPART_FORM_DATA
@@ -262,24 +250,20 @@
}
int requestSize = req.getContentLength();
- if (requestSize == -1)
- {
+ if (requestSize == -1) {
throw new UnknownSizeException(
"the request was rejected because it's size is unknown");
}
- if (sizeMax >= 0 && requestSize > sizeMax)
- {
+ if (sizeMax >= 0 && requestSize > sizeMax) {
throw new SizeLimitExceededException(
"the request was rejected because "
+ "it's size exceeds allowed range");
}
- try
- {
+ try {
String boundaryStr = getBoundary(contentType);
- if (boundaryStr == null)
- {
+ if (boundaryStr == null) {
throw new FileUploadException(
"the request was rejected because "
+ "no multipart boundary was found");
@@ -292,41 +276,31 @@
multi.setHeaderEncoding(headerEncoding);
boolean nextPart = multi.skipPreamble();
- while (nextPart)
- {
+ while (nextPart) {
Map headers = parseHeaders(multi.readHeaders());
String fieldName = getFieldName(headers);
- if (fieldName != null)
- {
+ if (fieldName != null) {
String subContentType = getHeader(headers, CONTENT_TYPE);
if (subContentType != null && subContentType
- .toLowerCase().startsWith(MULTIPART_MIXED))
- {
+ .toLowerCase().startsWith(MULTIPART_MIXED)) {
// Multiple files.
String subBoundaryStr = getBoundary(subContentType);
byte[] subBoundary = subBoundaryStr.getBytes();
multi.setBoundary(subBoundary);
boolean nextSubPart = multi.skipPreamble();
- while (nextSubPart)
- {
+ while (nextSubPart) {
headers = parseHeaders(multi.readHeaders());
- if (getFileName(headers) != null)
- {
+ if (getFileName(headers) != null) {
FileItem item =
createItem(headers, false);
OutputStream os = item.getOutputStream();
- try
- {
+ try {
multi.readBodyData(os);
- }
- finally
- {
+ } finally {
os.close();
}
items.add(item);
- }
- else
- {
+ } else {
// Ignore anything but files inside
// multipart/mixed.
multi.discardBodyData();
@@ -334,33 +308,24 @@
nextSubPart = multi.readBoundary();
}
multi.setBoundary(boundary);
- }
- else
- {
+ } else {
FileItem item = createItem(headers,
getFileName(headers) == null);
OutputStream os = item.getOutputStream();
- try
- {
+ try {
multi.readBodyData(os);
- }
- finally
- {
+ } finally {
os.close();
}
items.add(item);
}
- }
- else
- {
+ } else {
// Skip this part.
multi.discardBodyData();
}
nextPart = multi.readBoundary();
}
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
throw new FileUploadException(
"Processing of " + MULTIPART_FORM_DATA
+ " request failed. " + e.getMessage());
@@ -381,13 +346,12 @@
*
* @return The boundary, without any surrounding quotes.
*/
- protected String getBoundary(String contentType)
- {
+ protected String getBoundary(String contentType) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(contentType, ';');
- return (String)params.get("boundary");
+ return (String) params.get("boundary");
}
@@ -399,25 +363,19 @@
*
* @return The file name for the current <code>encapsulation</code>.
*/
- protected String getFileName(Map /* String, String */ headers)
- {
+ protected String getFileName(Map /* String, String */ headers) {
String fileName = null;
String cd = getHeader(headers, CONTENT_DISPOSITION);
- if (cd.startsWith(FORM_DATA) || cd.startsWith(ATTACHMENT))
- {
+ if (cd.startsWith(FORM_DATA) || cd.startsWith(ATTACHMENT)) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(cd, ';');
- if (params.containsKey("filename"))
- {
- fileName = (String)params.get("filename");
- if (fileName != null)
- {
+ if (params.containsKey("filename")) {
+ fileName = (String) params.get("filename");
+ if (fileName != null) {
fileName = fileName.trim();
- }
- else
- {
+ } else {
// Even if there is no value, the parameter is present, so
// we return an empty file name rather than no file name.
fileName = "";
@@ -436,20 +394,17 @@
*
* @return The field name for the current <code>encapsulation</code>.
*/
- protected String getFieldName(Map /* String, String */ headers)
- {
+ protected String getFieldName(Map /* String, String */ headers) {
String fieldName = null;
String cd = getHeader(headers, CONTENT_DISPOSITION);
- if (cd != null && cd.startsWith(FORM_DATA))
- {
+ if (cd != null && cd.startsWith(FORM_DATA)) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(cd, ';');
- fieldName = (String)params.get("name");
- if (fieldName != null)
- {
+ fieldName = (String) params.get("name");
+ if (fieldName != null) {
fieldName = fieldName.trim();
}
}
@@ -471,8 +426,7 @@
*/
protected FileItem createItem(Map /* String, String */ headers,
boolean isFormField)
- throws FileUploadException
- {
+ throws FileUploadException {
return getFileItemFactory().createItem(getFieldName(headers),
getHeader(headers, CONTENT_TYPE),
isFormField,
@@ -492,34 +446,27 @@
*
* @return A <code>Map</code> containing the parsed HTTP request headers.
*/
- protected Map /* String, String */ parseHeaders(String headerPart)
- {
+ protected Map /* String, String */ parseHeaders(String headerPart) {
Map headers = new HashMap();
- char buffer[] = new char[MAX_HEADER_SIZE];
+ char[] buffer = new char[MAX_HEADER_SIZE];
boolean done = false;
int j = 0;
int i;
String header, headerName, headerValue;
- try
- {
- while (!done)
- {
+ 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')
- {
+ 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(""))
- {
+ if (header.equals("")) {
done = true;
- }
- else
- {
- if (header.indexOf(':') == -1)
- {
+ } else {
+ if (header.indexOf(':') == -1) {
// This header line is malformed, skip it.
continue;
}
@@ -527,23 +474,18 @@
.trim().toLowerCase();
headerValue =
header.substring(header.indexOf(':') + 1).trim();
- if (getHeader(headers, headerName) != null)
- {
+ 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
- {
+ } else {
headers.put(headerName, headerValue);
}
}
}
- }
- catch (IndexOutOfBoundsException e)
- {
+ } catch (IndexOutOfBoundsException e) {
// Headers were malformed. continue with all that was
// parsed.
}
@@ -562,8 +504,7 @@
* there were multiple headers of that name.
*/
protected final String getHeader(Map /* String, String */ headers,
- String name)
- {
+ String name) {
return (String) headers.get(name.toLowerCase());
}
@@ -572,14 +513,12 @@
* Thrown to indicate that the request is not a multipart request.
*/
public static class InvalidContentTypeException
- extends FileUploadException
- {
+ extends FileUploadException {
/**
* Constructs a <code>InvalidContentTypeException</code> with no
* detail message.
*/
- public InvalidContentTypeException()
- {
+ public InvalidContentTypeException() {
super();
}
@@ -589,8 +528,7 @@
*
* @param message The detail message.
*/
- public InvalidContentTypeException(String message)
- {
+ public InvalidContentTypeException(String message) {
super(message);
}
}
@@ -600,14 +538,12 @@
* Thrown to indicate that the request size is not specified.
*/
public static class UnknownSizeException
- extends FileUploadException
- {
+ extends FileUploadException {
/**
* Constructs a <code>UnknownSizeException</code> with no
* detail message.
*/
- public UnknownSizeException()
- {
+ public UnknownSizeException() {
super();
}
@@ -617,8 +553,7 @@
*
* @param message The detail message.
*/
- public UnknownSizeException(String message)
- {
+ public UnknownSizeException(String message) {
super(message);
}
}
@@ -628,14 +563,12 @@
* Thrown to indicate that the request size exceeds the configured maximum.
*/
public static class SizeLimitExceededException
- extends FileUploadException
- {
+ extends FileUploadException {
/**
* Constructs a <code>SizeExceededException</code> with no
* detail message.
*/
- public SizeLimitExceededException()
- {
+ public SizeLimitExceededException() {
super();
}
@@ -645,8 +578,7 @@
*
* @param message The detail message.
*/
- public SizeLimitExceededException(String message)
- {
+ public SizeLimitExceededException(String message) {
super(message);
}
}
1.10 +4 -7 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUploadException.java
Index: FileUploadException.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/FileUploadException.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- FileUploadException.java 25 Feb 2004 21:07:12 -0000 1.9
+++ FileUploadException.java 29 Oct 2004 04:17:23 -0000 1.10
@@ -22,14 +22,12 @@
* @version $Id$
*/
public class FileUploadException
- extends Exception
-{
+ extends Exception {
/**
* Constructs a new <code>FileUploadException</code> without message.
*/
- public FileUploadException()
- {
+ public FileUploadException() {
}
/**
@@ -38,8 +36,7 @@
*
* @param msg the error message.
*/
- public FileUploadException(String msg)
- {
+ public FileUploadException(final String msg) {
super(msg);
}
}
1.17 +100 -162 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/MultipartStream.java
Index: MultipartStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/MultipartStream.java,v
retrieving revision 1.16
retrieving revision 1.17
diff -u -r1.16 -r1.17
--- MultipartStream.java 17 Oct 2004 00:58:35 -0000 1.16
+++ MultipartStream.java 29 Oct 2004 04:17:23 -0000 1.17
@@ -82,13 +82,30 @@
*
* @version $Id$
*/
-public class MultipartStream
-{
+public class MultipartStream {
// ----------------------------------------------------- Manifest constants
/**
+ * The Carriage Return ASCII character value.
+ */
+ public static final byte CR = 0x0D;
+
+
+ /**
+ * The Line Feed ASCII character value.
+ */
+ public static final byte LF = 0x0A;
+
+
+ /**
+ * The dash (-) ASCII character value.
+ */
+ public static final byte DASH = 0x2D;
+
+
+ /**
* The maximum length of <code>header-part</code> that will be
* processed (10 kilobytes = 10240 bytes.).
*/
@@ -105,21 +122,24 @@
* 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};
+ protected static final byte[] HEADER_SEPARATOR = {
+ CR, LF, CR, LF };
/**
* 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 };
+ protected static final byte[] FIELD_SEPARATOR = {
+ CR, LF};
/**
* 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 };
+ protected static final byte[] STREAM_TERMINATOR = {
+ DASH, DASH};
// ----------------------------------------------------------- Data members
@@ -194,8 +214,7 @@
* @see #MultipartStream(InputStream, byte[])
*
*/
- public MultipartStream()
- {
+ public MultipartStream() {
}
@@ -219,8 +238,7 @@
*/
public MultipartStream(InputStream input,
byte[] boundary,
- int bufSize)
- {
+ int bufSize) {
this.input = input;
this.bufSize = bufSize;
this.buffer = new byte[bufSize];
@@ -230,10 +248,10 @@
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;
+ this.boundary[0] = CR;
+ this.boundary[1] = LF;
+ this.boundary[2] = DASH;
+ this.boundary[3] = DASH;
System.arraycopy(boundary, 0, this.boundary, 4, boundary.length);
head = 0;
@@ -256,8 +274,7 @@
*/
public MultipartStream(InputStream input,
byte[] boundary)
- throws IOException
- {
+ throws IOException {
this(input, boundary, DEFAULT_BUFSIZE);
}
@@ -273,8 +290,7 @@
*
* @return The encoding used to read part headers.
*/
- public String getHeaderEncoding()
- {
+ public String getHeaderEncoding() {
return headerEncoding;
}
@@ -286,8 +302,7 @@
*
* @param encoding The encoding used to read part headers.
*/
- public void setHeaderEncoding(String encoding)
- {
+ public void setHeaderEncoding(String encoding) {
headerEncoding = encoding;
}
@@ -301,16 +316,13 @@
* @exception IOException if there is no more data available.
*/
public byte readByte()
- throws IOException
- {
+ throws IOException {
// Buffer depleted ?
- if (head == tail)
- {
+ if (head == tail) {
head = 0;
// Refill.
tail = input.read(buffer, head, bufSize);
- if (tail == -1)
- {
+ if (tail == -1) {
// No more data available.
throw new IOException("No more data is available");
}
@@ -330,17 +342,14 @@
* fails to follow required syntax.
*/
public boolean readBoundary()
- throws MalformedStreamException
- {
+ throws MalformedStreamException {
byte[] marker = new byte[2];
boolean nextChunk = false;
head += boundaryLength;
- try
- {
+ try {
marker[0] = readByte();
- if (marker[0] == 0x0A)
- {
+ if (marker[0] == LF) {
// Work around IE5 Mac bug with input type=image.
// Because the boundary delimiter, not including the trailing
// CRLF, must not appear within any file (RFC 2046, section
@@ -351,22 +360,15 @@
}
marker[1] = readByte();
- if (arrayequals(marker, STREAM_TERMINATOR, 2))
- {
+ if (arrayequals(marker, STREAM_TERMINATOR, 2)) {
nextChunk = false;
- }
- else if (arrayequals(marker, FIELD_SEPARATOR, 2))
- {
+ } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {
nextChunk = true;
- }
- else
- {
+ } else {
throw new MalformedStreamException(
"Unexpected characters follow a boundary");
}
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
throw new MalformedStreamException("Stream ended unexpectedly");
}
return nextChunk;
@@ -393,10 +395,8 @@
* being currently parsed.
*/
public void setBoundary(byte[] boundary)
- throws IllegalBoundaryException
- {
- if (boundary.length != boundaryLength - 4)
- {
+ throws IllegalBoundaryException {
+ if (boundary.length != boundaryLength - 4) {
throw new IllegalBoundaryException(
"The length of a boundary token can not be changed");
}
@@ -420,55 +420,40 @@
* @exception MalformedStreamException if the stream ends unexpecetedly.
*/
public String readHeaders()
- throws MalformedStreamException
- {
+ throws MalformedStreamException {
int i = 0;
- byte b[] = new byte[1];
+ 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
- {
+ while (i < 4) {
+ try {
b[0] = readByte();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
throw new MalformedStreamException("Stream ended unexpectedly");
}
size++;
- if (b[0] == HEADER_SEPARATOR[i])
- {
+ if (b[0] == HEADER_SEPARATOR[i]) {
i++;
- }
- else
- {
+ } else {
i = 0;
}
- if (size <= sizeMax)
- {
+ if (size <= sizeMax) {
baos.write(b[0]);
}
}
String headers = null;
- if (headerEncoding != null)
- {
- try
- {
+ if (headerEncoding != null) {
+ try {
headers = baos.toString(headerEncoding);
- }
- catch (UnsupportedEncodingException e)
- {
+ } catch (UnsupportedEncodingException e) {
// Fall back to platform default if specified encoding is not
// supported.
headers = baos.toString();
}
- }
- else
- {
+ } else {
headers = baos.toString();
}
@@ -494,35 +479,27 @@
*/
public int readBodyData(OutputStream output)
throws MalformedStreamException,
- IOException
- {
+ IOException {
boolean done = false;
int pad;
int pos;
int bytesRead;
int total = 0;
- while (!done)
- {
+ while (!done) {
// Is boundary token present somewere in the buffer?
pos = findSeparator();
- if (pos != -1)
- {
+ 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
- {
+ } else {
// Determine how much data should be kept in the
// buffer.
- if (tail - head > keepRegion)
- {
+ if (tail - head > keepRegion) {
pad = keepRegion;
- }
- else
- {
+ } else {
pad = tail - head;
}
// Write out the data belonging to the body-data.
@@ -537,12 +514,9 @@
bytesRead = input.read(buffer, pad, bufSize - pad);
// [pprrrrrrr]
- if (bytesRead != -1)
- {
+ if (bytesRead != -1) {
tail = pad + bytesRead;
- }
- else
- {
+ } 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.
@@ -573,34 +547,26 @@
*/
public int discardBodyData()
throws MalformedStreamException,
- IOException
- {
+ IOException {
boolean done = false;
int pad;
int pos;
int bytesRead;
int total = 0;
- while (!done)
- {
+ while (!done) {
// Is boundary token present somewere in the buffer?
pos = findSeparator();
- if (pos != -1)
- {
+ if (pos != -1) {
// Write the rest of the data before the boundary.
total += pos - head;
head = pos;
done = true;
- }
- else
- {
+ } else {
// Determine how much data should be kept in the
// buffer.
- if (tail - head > keepRegion)
- {
+ if (tail - head > keepRegion) {
pad = keepRegion;
- }
- else
- {
+ } else {
pad = tail - head;
}
total += tail - head - pad;
@@ -613,12 +579,9 @@
bytesRead = input.read(buffer, pad, bufSize - pad);
// [pprrrrrrr]
- if (bytesRead != -1)
- {
+ if (bytesRead != -1) {
tail = pad + bytesRead;
- }
- else
- {
+ } else {
// The last pad amount is left in the buffer.
// Boundary can't be in there so signal an error
// condition.
@@ -641,31 +604,25 @@
* @exception IOException if an i/o error occurs.
*/
public boolean skipPreamble()
- throws IOException
- {
+ 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
- {
+ try {
// Discard all data up to the delimiter.
discardBodyData();
// Read boundary - if succeded, the stream contains an
// encapsulation.
return readBoundary();
- }
- catch (MalformedStreamException e)
- {
+ } catch (MalformedStreamException e) {
return false;
- }
- finally
- {
+ } finally {
// Restore delimiter.
System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);
boundaryLength = boundary.length;
- boundary[0] = 0x0D;
- boundary[1] = 0x0A;
+ boundary[0] = CR;
+ boundary[1] = LF;
}
}
@@ -683,12 +640,9 @@
*/
public static boolean arrayequals(byte[] a,
byte[] b,
- int count)
- {
- for (int i = 0; i < count; i++)
- {
- if (a[i] != b[i])
- {
+ int count) {
+ for (int i = 0; i < count; i++) {
+ if (a[i] != b[i]) {
return false;
}
}
@@ -707,12 +661,9 @@
* <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)
- {
+ int pos) {
+ for (int i = pos; i < tail; i++) {
+ if (buffer[i] == value) {
return i;
}
}
@@ -729,30 +680,24 @@
* beginning of the <code>buffer</code>, or <code>-1</code> if
* not found.
*/
- protected int findSeparator()
- {
+ protected int findSeparator() {
int first;
int match = 0;
int maxpos = tail - boundaryLength;
for (first = head;
(first <= maxpos) && (match != boundaryLength);
- first++)
- {
+ first++) {
first = findByte(boundary[0], first);
- if (first == -1 || (first > maxpos))
- {
+ if (first == -1 || (first > maxpos)) {
return -1;
}
- for (match = 1; match < boundaryLength; match++)
- {
- if (buffer[first + match] != boundary[match])
- {
+ for (match = 1; match < boundaryLength; match++) {
+ if (buffer[first + match] != boundary[match]) {
break;
}
}
}
- if (match == boundaryLength)
- {
+ if (match == boundaryLength) {
return first - 1;
}
return -1;
@@ -763,8 +708,7 @@
*
* @return The string representation of this object.
*/
- public String toString()
- {
+ public String toString() {
StringBuffer sbTemp = new StringBuffer();
sbTemp.append("boundary='");
sbTemp.append(String.valueOf(boundary));
@@ -778,14 +722,12 @@
* required syntax.
*/
public class MalformedStreamException
- extends IOException
- {
+ extends IOException {
/**
* Constructs a <code>MalformedStreamException</code> with no
* detail message.
*/
- public MalformedStreamException()
- {
+ public MalformedStreamException() {
super();
}
@@ -795,8 +737,7 @@
*
* @param message The detail message.
*/
- public MalformedStreamException(String message)
- {
+ public MalformedStreamException(String message) {
super(message);
}
}
@@ -806,14 +747,12 @@
* Thrown upon attempt of setting an invalid boundary token.
*/
public class IllegalBoundaryException
- extends IOException
- {
+ extends IOException {
/**
* Constructs an <code>IllegalBoundaryException</code> with no
* detail message.
*/
- public IllegalBoundaryException()
- {
+ public IllegalBoundaryException() {
super();
}
@@ -823,8 +762,7 @@
*
* @param message The detail message.
*/
- public IllegalBoundaryException(String message)
- {
+ public IllegalBoundaryException(String message) {
super(message);
}
}
1.2 +72 -93 jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/ParameterParser.java
Index: ParameterParser.java
===================================================================
RCS file: /home/cvs/jakarta-commons/fileupload/src/java/org/apache/commons/fileupload/ParameterParser.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- ParameterParser.java 12 Mar 2004 07:34:46 -0000 1.1
+++ ParameterParser.java 29 Oct 2004 04:17:23 -0000 1.2
@@ -31,34 +31,41 @@
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*/
-public class ParameterParser
-{
- /** String to be parsed */
+public class ParameterParser {
+ /**
+ * String to be parsed.
+ */
private char[] chars = null;
- /** Current position in the string */
+ /**
+ * Current position in the string.
+ */
private int pos = 0;
- /** Maximum position in the string */
+ /**
+ * Maximum position in the string.
+ */
private int len = 0;
- /** Start of a token */
+ /**
+ * Start of a token.
+ */
private int i1 = 0;
- /** End of a token */
+ /**
+ * End of a token.
+ */
private int i2 = 0;
/**
- * Whether names stored in the map should be converted
- * to lower case
+ * Whether names stored in the map should be converted to lower case.
*/
private boolean lowerCaseNames = false;
/**
- * Default ParameterParser constructor
+ * Default ParameterParser constructor.
*/
- public ParameterParser()
- {
+ public ParameterParser() {
super();
}
@@ -68,8 +75,7 @@
* @return <tt>true</tt> if there are unparsed characters,
* <tt>false</tt> otherwise.
*/
- private boolean hasChar()
- {
+ private boolean hasChar() {
return this.pos < this.len;
}
@@ -82,39 +88,33 @@
* <tt>false</tt> otherwise.
* @return the token
*/
- private String getToken(boolean quoted)
- {
+ private String getToken(boolean quoted) {
// Trim leading white spaces
- while ((i1 < i2) && (Character.isWhitespace(chars[i1])))
- {
+ while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
i1++;
}
// Trim trailing white spaces
- while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1])))
- {
+ while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
i2--;
}
// Strip away quotation marks if necessary
- if (quoted)
- {
+ if (quoted) {
if (((i2 - i1) >= 2)
&& (chars[i1] == '"')
- && (chars[i2 - 1] == '"'))
- {
+ && (chars[i2 - 1] == '"')) {
i1++;
i2--;
}
}
String result = null;
- if (i2 > i1)
- {
+ if (i2 > i1) {
result = new String(chars, i1, i2 - i1);
}
return result;
}
/**
- * Tests if the given character is present in the array of characters
+ * Tests if the given character is present in the array of characters.
*
* @param ch the character to test for presense in the array of characters
* @param charray the array of characters to test against
@@ -122,13 +122,10 @@
* @return <tt>true</tt> if the character is present in the array of
* characters, <tt>false</tt> otherwise.
*/
- private boolean isOneOf(char ch, final char[] charray)
- {
+ private boolean isOneOf(char ch, final char[] charray) {
boolean result = false;
- for (int i = 0; i < charray.length; i++)
- {
- if (ch == charray[i])
- {
+ for (int i = 0; i < charray.length; i++) {
+ if (ch == charray[i]) {
result = true;
break;
}
@@ -145,16 +142,13 @@
*
* @return the token
*/
- private String parseToken(final char[] terminators)
- {
+ private String parseToken(final char[] terminators) {
char ch;
i1 = pos;
i2 = pos;
- while (hasChar())
- {
+ while (hasChar()) {
ch = chars[pos];
- if (isOneOf(ch, terminators))
- {
+ if (isOneOf(ch, terminators)) {
break;
}
i2++;
@@ -173,22 +167,18 @@
*
* @return the token
*/
- private String parseQuotedToken(final char[] terminators)
- {
+ private String parseQuotedToken(final char[] terminators) {
char ch;
i1 = pos;
i2 = pos;
boolean quoted = false;
boolean charEscaped = false;
- while (hasChar())
- {
+ while (hasChar()) {
ch = chars[pos];
- if (!quoted && isOneOf(ch, terminators))
- {
+ if (!quoted && isOneOf(ch, terminators)) {
break;
}
- if (!charEscaped && ch == '"')
- {
+ if (!charEscaped && ch == '"') {
quoted = !quoted;
}
charEscaped = (!charEscaped && ch == '\\');
@@ -200,44 +190,40 @@
}
/**
- * Returns <tt>true</tt> if parameter names are to be
- * converted to lower case when name/value pairs are parsed
- *
- * @return <tt>true</tt> if parameter names are to be
- * converted to lower case when name/value pairs are parsed.
- * Otherwise returns <tt>false</tt>
- */
- public boolean isLowerCaseNames()
- {
+ * Returns <tt>true</tt> if parameter names are to be converted to lower
+ * case when name/value pairs are parsed.
+ *
+ * @return <tt>true</tt> if parameter names are to be
+ * converted to lower case when name/value pairs are parsed.
+ * Otherwise returns <tt>false</tt>
+ */
+ public boolean isLowerCaseNames() {
return this.lowerCaseNames;
}
/**
- * Sets the flag if parameter names are to be converted to
- * lower case when name/value pairs are parsed
- *
- * @param b <tt>true</tt> if parameter names are to be
- * converted to lower case when name/value pairs are parsed.
- * <tt>false</tt> otherwise.
- */
- public void setLowerCaseNames(boolean b)
- {
+ * Sets the flag if parameter names are to be converted to lower case when
+ * name/value pairs are parsed.
+ *
+ * @param b <tt>true</tt> if parameter names are to be
+ * converted to lower case when name/value pairs are parsed.
+ * <tt>false</tt> otherwise.
+ */
+ public void setLowerCaseNames(boolean b) {
this.lowerCaseNames = b;
}
/**
- * Extracts a map of name/value pairs from the given string.
- * Names are expected to be unique
+ * Extracts a map of name/value pairs from the given string. Names are
+ * expected to be unique.
*
* @param str the string that contains a sequence of name/value pairs
* @param separator the name/value pairs separator
*
* @return a map of name/value pairs
*/
- public Map parse(final String str, char separator)
- {
- if (str == null)
- {
+ public Map parse(final String str, char separator) {
+ if (str == null) {
return new HashMap();
}
return parse(str.toCharArray(), separator);
@@ -245,7 +231,7 @@
/**
* Extracts a map of name/value pairs from the given array of
- * characters. Names are expected to be unique
+ * characters. Names are expected to be unique.
*
* @param chars the array of characters that contains a sequence of
* name/value pairs
@@ -253,10 +239,8 @@
*
* @return a map of name/value pairs
*/
- public Map parse(final char[] chars, char separator)
- {
- if (chars == null)
- {
+ public Map parse(final char[] chars, char separator) {
+ if (chars == null) {
return new HashMap();
}
return parse(chars, 0, chars.length, separator);
@@ -264,7 +248,7 @@
/**
* Extracts a map of name/value pairs from the given array of
- * characters. Names are expected to be unique
+ * characters. Names are expected to be unique.
*
* @param chars the array of characters that contains a sequence of
* name/value pairs
@@ -278,11 +262,9 @@
final char[] chars,
int offset,
int length,
- char separator)
- {
+ char separator) {
- if (chars == null)
- {
+ if (chars == null) {
return new HashMap();
}
HashMap params = new HashMap();
@@ -292,23 +274,20 @@
String paramName = null;
String paramValue = null;
- while (hasChar())
- {
- paramName = parseToken(new char[] { '=', separator });
+ while (hasChar()) {
+ paramName = parseToken(new char[] {
+ '=', separator });
paramValue = null;
- if (hasChar() && (chars[pos] == '='))
- {
+ if (hasChar() && (chars[pos] == '=')) {
pos++; // skip '='
- paramValue = parseQuotedToken(new char[] { separator });
+ paramValue = parseQuotedToken(new char[] {
+ separator });
}
- if (hasChar() && (chars[pos] == separator))
- {
+ if (hasChar() && (chars[pos] == separator)) {
pos++; // skip separator
}
- if ((paramName != null) && (paramName.length() > 0))
- {
- if (this.lowerCaseNames)
- {
+ if ((paramName != null) && (paramName.length() > 0)) {
+ if (this.lowerCaseNames) {
paramName = paramName.toLowerCase();
}
params.put(paramName, paramValue);
---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org