com.braintreegateway.RequestBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of org.apache.servicemix.bundles.braintree-java
Show all versions of org.apache.servicemix.bundles.braintree-java
This OSGi bundle wraps ${pkgArtifactId} ${pkgVersion} jar file.
The newest version!
package com.braintreegateway;
import com.braintreegateway.util.QueryString;
import com.braintreegateway.util.StringUtils;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
public class RequestBuilder {
private String parent;
private List> topLevelElements;
private List> elements;
public RequestBuilder(String parent) {
this.parent = parent;
this.topLevelElements = new ArrayList>();
this.elements = new ArrayList>();
}
public RequestBuilder addTopLevelElement(String name, String value) {
topLevelElements.add(new AbstractMap.SimpleEntry(name, value));
return this;
}
public RequestBuilder addElement(String name, Object value) {
elements.add(new AbstractMap.SimpleEntry(name, value));
return this;
}
public String toQueryString() {
QueryString queryString = new QueryString();
for (Map.Entry entry : topLevelElements) {
queryString.append(StringUtils.underscore(entry.getKey()), entry.getValue());
}
for (Map.Entry entry : elements) {
queryString.append(parentBracketChildString(StringUtils.underscore(parent), StringUtils.underscore(entry.getKey())), entry.getValue());
}
return queryString.toString();
}
public String toXML() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("<%s>", parent));
for (Map.Entry entry : elements) {
builder.append(buildXMLElement(entry.getKey(), entry.getValue()));
}
builder.append(String.format("%s>", parent));
return builder.toString();
}
protected static String buildXMLElement(Object element) {
return buildXMLElement("", element);
}
@SuppressWarnings("unchecked")
protected static String buildXMLElement(String name, Object element) {
if (element == null) {
return "";
} else if (element instanceof Request) {
return ((Request) element).toXML();
} else if (element instanceof Calendar) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return String.format("<%s type=\"datetime\">%s%s>", name, dateFormat.format(((Calendar) element).getTime()), name);
} else if (element instanceof Map, ?>) {
return formatAsXML(name, (Map) element);
} else if (element instanceof List>) {
StringBuilder xml = new StringBuilder();
for (Object item : (List