Refactoring, in preparation for functional pieces for HTTPCLIENT-1372.

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1494902 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Karl Wright 2013-06-20 09:59:33 +00:00
parent eeba3e364d
commit 74213fa419
9 changed files with 489 additions and 18 deletions

View File

@ -0,0 +1,87 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* 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.http.entity.mime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.util.Args;
import org.apache.http.util.ByteArrayBuffer;
/**
* HttpBrowserCompatibleMultipart represents a collection of MIME multipart encoded content bodies. This class is
* emulates browser compatibility, e.g. IE 5 or earlier.
*
* @since 4.3
*/
public class HttpBrowserCompatibleMultipart extends HttpMultipartForm {
/**
* Creates an instance with the specified settings.
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpBrowserCompatibleMultipart(final String subType, final Charset charset, final String boundary) {
super(subType, charset, boundary);
}
public HttpBrowserCompatibleMultipart(final String subType, final String boundary) {
this(subType, null, boundary);
}
/**
* Write the multipart header fields; depends on the style.
*/
@Override
protected void formatMultipartHeader(
final FormBodyPart part,
final OutputStream out) throws IOException {
// For browser-compatible, only write Content-Disposition
// Use content charset
final Header header = part.getHeader();
final MinimalField cd = header.getField(MIME.CONTENT_DISPOSITION);
writeField(cd, this.charset, out);
final String filename = part.getBody().getFilename();
if (filename != null) {
final MinimalField ct = header.getField(MIME.CONTENT_TYPE);
writeField(ct, this.charset, out);
}
}
}

View File

@ -47,6 +47,7 @@ import org.apache.http.util.ByteArrayBuffer;
*
* @since 4.0
*/
@Deprecated
public class HttpMultipart {
private static ByteArrayBuffer encode(

View File

@ -0,0 +1,57 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* 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.http.entity.mime;
import java.nio.charset.Charset;
/**
*
* @since 4.3
*/
public class HttpMultipartFactory {
/** Non-instantiable */
private HttpMultipartFactory() {
}
/** Create an appropriate HttpMultipartForm instance */
public static HttpMultipartForm getInstance(
final String subType, final Charset charset, final String boundary,
final HttpMultipartMode mode) {
// If needed, this can be replaced with a registry in time
switch (mode) {
case STRICT:
return new HttpStrictMultipart(subType, charset, boundary);
case BROWSER_COMPATIBLE:
return new HttpBrowserCompatibleMultipart(subType, charset, boundary);
default:
throw new IllegalArgumentException("Unknown multipart mode");
}
}
}

View File

@ -0,0 +1,227 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* 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.http.entity.mime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.util.Args;
import org.apache.http.util.ByteArrayBuffer;
/**
* HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
* capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
* the browser compatible modes.
*
* @since 4.3
*/
public abstract class HttpMultipartForm {
private static ByteArrayBuffer encode(
final Charset charset, final String string) {
final ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
final ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
bab.append(encoded.array(), encoded.position(), encoded.remaining());
return bab;
}
private static void writeBytes(
final ByteArrayBuffer b, final OutputStream out) throws IOException {
out.write(b.buffer(), 0, b.length());
}
private static void writeBytes(
final String s, final Charset charset, final OutputStream out) throws IOException {
final ByteArrayBuffer b = encode(charset, s);
writeBytes(b, out);
}
private static void writeBytes(
final String s, final OutputStream out) throws IOException {
final ByteArrayBuffer b = encode(MIME.DEFAULT_CHARSET, s);
writeBytes(b, out);
}
protected static void writeField(
final MinimalField field, final OutputStream out) throws IOException {
writeBytes(field.getName(), out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), out);
writeBytes(CR_LF, out);
}
protected static void writeField(
final MinimalField field, final Charset charset, final OutputStream out) throws IOException {
writeBytes(field.getName(), charset, out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), charset, out);
writeBytes(CR_LF, out);
}
private static final ByteArrayBuffer FIELD_SEP = encode(MIME.DEFAULT_CHARSET, ": ");
private static final ByteArrayBuffer CR_LF = encode(MIME.DEFAULT_CHARSET, "\r\n");
private static final ByteArrayBuffer TWO_DASHES = encode(MIME.DEFAULT_CHARSET, "--");
private final String subType;
protected final Charset charset;
private final String boundary;
private final List<FormBodyPart> parts;
/**
* Creates an instance with the specified settings.
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @param mode the mode to use
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpMultipartForm(final String subType, final Charset charset, final String boundary) {
super();
Args.notNull(subType, "Multipart subtype");
Args.notNull(boundary, "Multipart boundary");
this.subType = subType;
this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
this.boundary = boundary;
this.parts = new ArrayList<FormBodyPart>();
}
public HttpMultipartForm(final String subType, final String boundary) {
this(subType, null, boundary);
}
public String getSubType() {
return this.subType;
}
public Charset getCharset() {
return this.charset;
}
public List<FormBodyPart> getBodyParts() {
return this.parts;
}
public void addBodyPart(final FormBodyPart part) {
if (part == null) {
return;
}
this.parts.add(part);
}
public String getBoundary() {
return this.boundary;
}
private void doWriteTo(
final OutputStream out,
final boolean writeContent) throws IOException {
final ByteArrayBuffer boundary = encode(this.charset, getBoundary());
for (final FormBodyPart part: this.parts) {
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(CR_LF, out);
formatMultipartHeader(part, out);
writeBytes(CR_LF, out);
if (writeContent) {
part.getBody().writeTo(out);
}
writeBytes(CR_LF, out);
}
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(TWO_DASHES, out);
writeBytes(CR_LF, out);
}
/**
* Write the multipart header fields; depends on the style.
*/
protected abstract void formatMultipartHeader(
final FormBodyPart part,
final OutputStream out) throws IOException;
/**
* Writes out the content in the multipart/form encoding. This method
* produces slightly different formatting depending on its compatibility
* mode.
*
* @see #getMode()
*/
public void writeTo(final OutputStream out) throws IOException {
doWriteTo(out, true);
}
/**
* Determines the total length of the multipart content (content length of
* individual parts plus that of extra elements required to delimit the parts
* from one another). If any of the @{link BodyPart}s contained in this object
* is of a streaming entity of unknown length the total length is also unknown.
* <p/>
* This method buffers only a small amount of data in order to determine the
* total length of the entire entity. The content of individual parts is not
* buffered.
*
* @return total length of the multipart entity if known, <code>-1</code>
* otherwise.
*/
public long getTotalLength() {
long contentLen = 0;
for (final FormBodyPart part: this.parts) {
final ContentBody body = part.getBody();
final long len = body.getContentLength();
if (len >= 0) {
contentLen += len;
} else {
return -1;
}
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
doWriteTo(out, false);
final byte[] extra = out.toByteArray();
return contentLen + extra.length;
} catch (final IOException ex) {
// Should never happen
return -1;
}
}
}

View File

@ -0,0 +1,82 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* 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.http.entity.mime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.util.Args;
import org.apache.http.util.ByteArrayBuffer;
/**
* HttpStrictMultipart represents a collection of MIME multipart encoded content bodies, implementing the
* strict (RFC 822, RFC 2045, RFC 2046 compliant) interpretation of the spec.
*
* @since 4.3
*/
public class HttpStrictMultipart extends HttpMultipartForm {
/**
* Creates an instance with the specified settings.
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpStrictMultipart(final String subType, final Charset charset, final String boundary) {
super(subType, charset, boundary);
}
public HttpStrictMultipart(final String subType, final String boundary) {
this(subType, null, boundary);
}
/**
* Write the multipart header fields; depends on the style.
*/
@Override
protected void formatMultipartHeader(
final FormBodyPart part,
final OutputStream out) throws IOException {
// For strict, we output all fields with mime-standard encoding.
final Header header = part.getHeader();
for (final MinimalField field: header) {
writeField(field, out);
}
}
}

View File

@ -53,7 +53,7 @@ public class MultipartEntity implements HttpEntity {
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
private final HttpMultipart multipart;
private final HttpMultipartForm multipart;
private final Header contentType;
// @GuardedBy("dirty") // we always read dirty before accessing length
@ -72,8 +72,24 @@ public class MultipartEntity implements HttpEntity {
final Charset charset) {
super();
final String b = boundary != null ? boundary : generateBoundary();
final HttpMultipartMode m = mode != null ? mode : HttpMultipartMode.STRICT;
this.multipart = new HttpMultipart("form-data", charset, b, m);
this.multipart = HttpMultipartFactory.getInstance("form-data", charset, b, mode != null ? mode : HttpMultipartMode.STRICT);
this.contentType = new BasicHeader(HTTP.CONTENT_TYPE, generateContentType(b, charset));
this.dirty = true;
}
/**
* Creates an instance using the specified parameters
* @param multipart the part encoder to use, may not be {@code null}
* @param boundary the boundary string, may be {@code null}, in which case {@link #generateBoundary()} is invoked to create the string
* @param charset the character set to use, may be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
*/
public MultipartEntity(
final HttpMultipartForm multipart,
final String boundary,
final Charset charset) {
super();
final String b = boundary != null ? boundary : generateBoundary();
this.multipart = multipart;
this.contentType = new BasicHeader(HTTP.CONTENT_TYPE, generateContentType(b, charset));
this.dirty = true;
}
@ -120,7 +136,7 @@ public class MultipartEntity implements HttpEntity {
/**
* @since 4.3
*/
protected HttpMultipart getMultipart() {
protected HttpMultipartForm getMultipart() {
return multipart;
}

View File

@ -45,10 +45,10 @@ import org.apache.http.util.Args;
*/
public class MultipartEntityBuilder {
private boolean lax;
private String boundary;
private Charset charset;
private List<FormBodyPart> bodyParts;
private HttpMultipartMode mode = HttpMultipartMode.STRICT;
private String boundary = null;
private Charset charset = null;
private List<FormBodyPart> bodyParts = null;
public static MultipartEntityBuilder create() {
return new MultipartEntityBuilder();
@ -59,12 +59,12 @@ public class MultipartEntityBuilder {
}
public MultipartEntityBuilder setLaxMode() {
this.lax = true;
this.mode = HttpMultipartMode.BROWSER_COMPATIBLE;
return this;
}
public MultipartEntityBuilder setStrictMode() {
this.lax = false;
this.mode = HttpMultipartMode.STRICT;
return this;
}
@ -140,7 +140,7 @@ public class MultipartEntityBuilder {
public MultipartEntity build() {
final MultipartEntity e = new MultipartEntity(
this.lax ? HttpMultipartMode.BROWSER_COMPATIBLE : HttpMultipartMode.STRICT,
this.mode,
this.boundary, this.charset);
if (this.bodyParts != null) {
for (final FormBodyPart bp: this.bodyParts) {

View File

@ -41,7 +41,7 @@ public class TestMultipartEntityBuilder {
public void testBasics() throws Exception {
final MultipartEntity entity = MultipartEntityBuilder.create().build();
Assert.assertNotNull(entity);
Assert.assertEquals(HttpMultipartMode.STRICT, entity.getMultipart().getMode());
Assert.assertEquals("org.apache.http.entity.mime.HttpStrictMultipart", entity.getMultipart().getClass().getName());
Assert.assertEquals(0, entity.getMultipart().getBodyParts().size());
}
@ -53,7 +53,7 @@ public class TestMultipartEntityBuilder {
.setLaxMode()
.build();
Assert.assertNotNull(entity);
Assert.assertEquals(HttpMultipartMode.BROWSER_COMPATIBLE, entity.getMultipart().getMode());
Assert.assertEquals("org.apache.http.entity.mime.HttpBrowserCompatibleMultipart", entity.getMultipart().getClass().getName());
Assert.assertEquals("blah-blah", entity.getMultipart().getBoundary());
Assert.assertEquals(Consts.UTF_8, entity.getMultipart().getCharset());
}

View File

@ -46,7 +46,7 @@ public class TestMultipartForm {
@Test
public void testMultipartFormStringParts() throws Exception {
final HttpMultipart multipart = new HttpMultipart("form-data", "foo");
final HttpMultipartForm multipart = new HttpStrictMultipart("form-data", "foo");
final FormBodyPart p1 = new FormBodyPart(
"field1",
new StringBody("this stuff", ContentType.DEFAULT_TEXT));
@ -102,7 +102,7 @@ public class TestMultipartForm {
writer.close();
}
final HttpMultipart multipart = new HttpMultipart("form-data", "foo");
final HttpMultipartForm multipart = new HttpStrictMultipart("form-data", "foo");
final FormBodyPart p1 = new FormBodyPart(
"field1",
new FileBody(tmpfile));
@ -151,7 +151,8 @@ public class TestMultipartForm {
writer.close();
}
final HttpMultipart multipart = new HttpMultipart("form-data", null, "foo", HttpMultipartMode.STRICT);
// Strict is no accident here, despite the test name - otherwise Transfer-Encoding is not produced.
final HttpMultipartForm multipart = new HttpStrictMultipart("form-data", null, "foo");
final FormBodyPart p1 = new FormBodyPart(
"field1",
new FileBody(tmpfile));
@ -233,7 +234,7 @@ public class TestMultipartForm {
writer.close();
}
final HttpMultipart multipart = new HttpMultipart("form-data", Charset.forName("UTF-8"), "foo", HttpMultipartMode.BROWSER_COMPATIBLE);
final HttpMultipartForm multipart = new HttpBrowserCompatibleMultipart("form-data", Charset.forName("UTF-8"), "foo");
final FormBodyPart p1 = new FormBodyPart(
"field1",
new InputStreamBody(new FileInputStream(tmpfile), s1 + ".tmp"));
@ -274,7 +275,7 @@ public class TestMultipartForm {
final String s1 = constructString(SWISS_GERMAN_HELLO);
final String s2 = constructString(RUSSIAN_HELLO);
final HttpMultipart multipart = new HttpMultipart("form-data", "foo");
final HttpMultipartForm multipart = new HttpStrictMultipart("form-data", "foo");
final FormBodyPart p1 = new FormBodyPart(
"field1",
new StringBody(s1, ContentType.create("text/plain", Charset.forName("ISO-8859-1"))));