1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package com.p4square.ccbapi.serializer;
import com.p4square.ccbapi.model.Address;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Encode an Address object as form data for CCB.
*/
public class AddressFormSerializer implements Serializer<Address> {
@Override
public String encode(final Address address) {
final StringBuilder sb = new StringBuilder();
encode(address, sb);
return sb.toString();
}
@Override
public void encode(final Address address, final StringBuilder builder) {
// Sanity check.
if (address.getType() == null) {
throw new IllegalArgumentException("Address type cannot be null");
}
// Every form field will be prefixed with the type.
final String type = address.getType().toString().toLowerCase();
if (address.getStreetAddress() != null) {
appendField(builder, type, "street_address", address.getStreetAddress());
}
if (address.getCity() != null) {
appendField(builder, type, "city", address.getCity());
}
if (address.getState() != null) {
appendField(builder, type, "state", address.getState());
}
if (address.getZip() != null) {
appendField(builder, type, "zip", address.getZip());
}
if (address.getCountry() != null) {
appendField(builder, type, "country", address.getCountry().getCountryCode());
}
}
private void appendField(final StringBuilder builder, final String type, final String key, final String value) {
if (builder.length() > 0) {
builder.append("&");
}
try {
builder.append(type).append("_").append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 encoding should always be available.");
}
}
}
|