com.lyncode.test.http.method.MethodBuilder Maven / Gradle / Ivy
/**
* 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.
*/
package com.lyncode.test.http.method;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.lyncode.builder.Builder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
import static com.lyncode.test.util.Paths.path;
public abstract class MethodBuilder implements Builder {
private static final String SEPARATOR = "&";
private static final String ATTRIBUTION = "=";
private String baseUrl;
private final String relativeUrl;
private final List queryParams = new ArrayList();
private final List headers = new ArrayList();
public MethodBuilder setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
return this;
}
public MethodBuilder(String relativeUrl) {
this.relativeUrl = relativeUrl;
}
public Type with (String key, Object value) {
this.queryParams.add(new BasicNameValuePair(key, String.valueOf(value)));
return self();
}
public Type with (Header header) {
this.headers.add(header);
return self();
}
protected Type self() {
return (Type) this;
}
abstract T build (String url);
@Override
public T build() {
String url = path(baseUrl, relativeUrl);
if (!queryParams.isEmpty())
url += "?" + StringUtils.join(Collections2.transform(queryParams, pairToString()), SEPARATOR);
T build = build(url);
build.setHeaders(headers.toArray(new Header[headers.size()]));
return build;
}
private Function pairToString() {
return new Function() {
@Override
public String apply(NameValuePair input) {
return input.getName() + ATTRIBUTION + input.getValue();
}
};
}
}