HTTP Parts
The org.apache.juneau.http.part package contains implementations of
org.apache.http.NameValuePair
to be used for query/form-data/path parts and part lists.
PartList
The PartList class is a list of HTTP parts (form-data, query-parameters, path-parameters).
PartList parts = PartList
.create()
.append(MyPart.of("foo"))
.append("Bar", ()->getDynamicValueFromSomewhere());
Convenience creators are provided for creating lists with minimal code:
PartList parts = PartList.of(BasicIntegerPart.of("foo", 1));
Static methods are provided on HttpParts to further simplify creation of part lists.
import static org.apache.juneau.http.HttpParts.*;
PartList parts = partList(integerPart("foo", 1), booleanPart("bar", false));
The builder class supports setting default part values (i.e. add a part to the list if it isn't otherwise in the list). Note that this is different from simply setting a value twice as using default values will not overwrite existing parts.
The following example notes the distinction:
parts = PartList
.create()
.set("Foo", "bar")
.set("Foo", "baz");
assertObject(parts).isString("foo=baz");
parts = PartList
.create()
.set("Foo", "bar")
.setDefault("Foo", "baz");
assertObject(parts).isString("foo=bar");
Various methods are provided for iterating over the parts in this list to avoid array copies.
- forEach(Consumer) / forEach(String,Consumer) / forEach(Predicate,Consumer) - Use consumers to process parts.
- partIterator() / partIterator(String) - Use an PartIterator to process parts.
- stream() / stream(String) - Use a stream.
In general, try to use these over the getAll() / getAll(String) methods that require array copies. Similar to the way multiple headers can be collapsed into a single value, the get(String) method is special in that it will collapse multiple parts with the same name into a single comma-delimited list.
The get(Class) and get(String,Class) methods are provided for working with FormData / Query / Path-annotated beans.
MyQueryBean foo = parts.get(MyQueryBean.class);
A VarResolver can be associated with this builder to create part values with embedded variables that are resolved at runtime.
// Create a part list with dynamically-resolving values pulled from a system property.
System.setProperty("foo", "bar");
PartList parts = PartList
.create()
.resolving()
.append("X1", "$S{foo}")
.append("X2", ()->"$S{foo}");
assertObject(parts).isString("X1=bar&X2=bar");
The PartList object can be extended to defined pre-packaged lists of parts which can be used in various annotations throughout the framework.
// A predefined list of parts.
public class MyPartList extends PartList {
public MyPartList() {
super(BasicIntegerPart.of("foo",1), BasicBooleanPart.of("bar",false));
}
}